I am trying get type of property of my class by using of reflection but its returning my only RuntimePropertyInfo - as a name of a type.
I have object MyObject actualData - it contains property - "name" as string and "Item" as my type DatumType
When I am debugging I can see, that actualData has 2 properties, first one is type of string and second one is DatumType, but when I use this:
string typeName = actualData.getType().getProperty("Item").getType().Name - it returns me RuntimePropertyInfo, not DatumType
Can you see what am I doing wrong? I am using C# - .Net 4.0.
Thanks a lot!
You're getting the type of the PropertyInfo object getProperty() returns. Try
string typeName = actualData.getType().getProperty("Item").PropertyType.Name;
If you want the type of the value currently assigned to the object via the PropertyInfo object, you could call:
string typeName = actualData.getType().getProperty("Item").GetValue(actualData, null).GetType().Name;
But in that case you could also simply call:
string typeName = actualData.Item.GetType().Name;
The
actualData.getType().getProperty("Item")
retrieves something of type PropertyInfo.
If you then ask for its type:
actualData.getType().getProperty("Item").getType()
you get exactly what you observe you get.
I suspect this last getType() is not necessary then.
Edit: someone has downvoted this answer which is unfair imho. The question is "Can you see what am I doing wrong?" and the answer of being one getType too far is a correct one. Finding PropertyType in PropertyInfo is then easy if the asking person knows what he is doing wrong.
To the person who downvoted this answer: please at least leave a comment next time you downvote something. Stackoverflow makes sense only if we learn from each other, not just bash everyone around.
GetType() return always the type of the current object, not the pointed object.
In your case, consider using string typeName = actualData.getType().getProperty("Item").PropertyType.Name
Related
Let's say I have:
string ValueToCastTo;
object TheThing;
If ValueToCastTo is set to "int", I want TheThing to be casted to an int.
If ValueToCastTo is set to "DateTime", I want TheThing to be casted to a DateTime.
I can't use if statements because the string could be set to anything.
Thanks.
You'll need:
Type.GetType(string)
plus a built-in list corresponding to C# keywords, since GetType expects System.Int32 not int.
Convert.ChangeType(object, Type)
Maybe the runtime will figure out the right conversion, but normally it won't. So also write a whole lot of TypeConverter implementations and then use
TypeDescriptor.GetConverter(Type) followed by either TypeConverter.ConvertFrom(object) or TypeConverter.ConvertTo(object, Type) depending on which type knows about the other one
and when you're done, the static type will still be object. But it'll be a handle to an instance of your new type. Whether that helps you depends on exactly what you want to do with it...
TypeOf() you can use to get the type and then do reflection.
"C# - Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace."
You can follow that path to get what you want.
Hope that helps!
Short answer: you can't.
A cast is something you have to write at compile time, to assign a variable of type X an object of type Y.
A cast imply that you know at compile time the type you want to assign to, so you can write something such
int x = (int) y;
string x = (string) y;
There are workarounds to this: use TypeOf() on your object, use reflection to detect at runtime type, properties and methods of the object, or use dynamic to avoid compile time checks.
But it actually depends on what you are trying to get from your code.
I've scanned many topics on this site, searched the internet, and experimented with code and nothing has worked. Most people are using separate projects or assemblies which I am not, it's a custom class that exists in the same project and same namespace. If I build the object manually by hard coding it in it works fine but I don't want to do that.
It's a C# ASPX project and I am debugging on IIS from Visual Studio (so maybe that's the issue?).
Type type = Type.GetType("<namespace>."+classname);
Object obj = Activator.CreateInstance(type);
MethodInfo methodInfo = type.GetMethod(function);
response = (<cast object>)(methodInfo.Invoke(obj, null));
I am aiming for variable code where I can write plugins that will be dynamically instantiated. Type.GetType always returns null.
In almost all cases type returns null or when I switch it up with other code I'll get other errors thrown about not finding file or assembly and other errors like this class just doesn't exist...
What do I have to do to be able to build an object dynamically off a string? Let's say I have a class called "Foobar" and I want to do this,
string classname = "Foobar";
Object foobar = new classname(); //easy in PHP, nightmare in C#
Any help would be great, thanks. And before you tell me just to reference another post, I have referenced many and still have no success so if it's not the code than maybe it's how I'm debugging in a browser on IIS?
Type.GetType(String) accepts assembly-qualified type name.
See Type.AssemblyQualifiedName Property
You need to get the type from the assembly is was defined in:
typeof(SomeTypeInAssembly).Assembly.GetType("Namespace.Type")
If it is in the same namespace and assembly as the current object as you say, you should just be able to do the following to get hold of the Type you require:
Type type = Type.GetType(this.GetType().Namespace + "." + classname);
The rest should work as you have it.
Thanks for the suggestions, final code I ended up with below from the suggestions and other post I found on this site.
string fullname = string.Format("{0}.{1}", this.GetType().Namespace, classname);
Type type = Type.GetType(fullname,true);
Baseclass class = (BaseClass)Activator.CreateInstance(type,<parameter1>,...);
MethodInfo methodInfo = type.GetMethod("<method>");
methodInfo.Invoke(class, null);
You can store the return (may need casting) if you want to deal with the return type. Hope this helps someone if they're having issues like me.
Thanks to Rhumborl post, I guess it was an issue in just how I was originally trying to call the Type.GetType function.
String is a native type , witch is automatically inherited from object , since every type (aka class) is an object, so there is no need to do such a thing
Is it possible to test if a variable is defined as a string if the value inside it is null?
If I write:
string b = null;
bool c = b is string;
Then c will be false because is looks at the content, which is null and not a string.
If I write:
string b = null;
bool c = (b.GetType() == typeof(string));
Then it crashes because s is null and you can't call GetType() on a null value.
So, how can I check b to find out what type it is? Some kind of reflection maybe? Or is there any simpler way?
Edit 1: Clarification of the question!
I was a bit unclear in my question and that was my fault. In the example it looks like I'm trying to test the content of the variable. But I want to test the variable itself without looking at the content. In the code examples given I can see that b is a string, but what if I don't know if b is a string and just want to test the variable s to see if it is a string or not.
So, how can I know what type the variable is defined as? As in this example, but x is an unknown variable that might be defined as a string and it might be null as well (since it might be null this example won't work).
bool c = (x.GetType() == typeof(string));
Edit 2: The working solution!
Thanks to all the answers given I was able to solve it. This is how the working solution became. I first created a help function to test the defined type of a variable that works even if the value is null and it doesn't point to anything.
public static Type GetParameterType<T>(T destination)
{
return typeof(T);
}
Then I can just call this function and test my "suspected string" and find out if it really is a string or not.
// We define s as string just for this examples sake but in my "definition" we wouldn't be sure about whether s is a string or not.
string s = null;
// Now we want to test to see if s is a string
Type t = GetParameterType(s);
b = t == typeof(string); // Returns TRUE because s has the type of a string
b = t is string; // Returns FALSE because the content isn't a string
This is just what I wanted to find out!!! Thank you all for squeezing your brains...
You cannot check the type of null because null has no type. It doesn't reference anything at all, therefore there is nothing that C# can look at to find out the actual type.
(Everyone else seems to be answering the question "How can I tell if a string reference is null or empty - but I think the question is "how can I tell if the underlying type of a null reference is string...)
There might be a way to fiddle it though - you might be able to use a generic method as mentioned here:
.NET : How do you get the Type of a null object?
(That link was posted by someone else - not me - as a comment to your original post!)
So you want to know if there is a direct method to check of an object type whose value is set to NULL
In The simple word the answer is NO.
A null reference does not point to any Storage Location, so there is no metadata from which it can make that determination.
Although if you already know it is of type String , you can use following two functions for checking null values
String.IsNullOrWhiteSpace(stringObject);
and
String.IsNullOrEmpty(stringObject)
The best that you could do to set a value to unknown type is use
Convert.ChangeType
e.g. as given in .NET : How do you get the Type of a null object?
public void GetObjectValue<T>(out T destination)
{
object paramVal = "Blah.Blah.";
destination = default(T);
destination = Convert.ChangeType(paramVal, typeof(T).GetType());
}
The type of T can be inferred, so you shouldn't need to give a type parameter to the method explicitly.
Here it is
String.IsNullOrEmpty(s);
If you want to tell whether the actual value is a string, you can't do that with null, as null doesn't have a type.
So it seems you want to determine the actual type of the variable (the one it was declared as):
If the variable is of type string, then you know it at compile time (you declared it as string, after all).
If the variable is generic (like in generic types or a generic method), you can test it via typeof(T), assuming T is your type parameter.
If you got the variable as object though (e.g. as argument of a method), then there is no way to determine its original type if its value is null.
Use the String.IsNullOrEmpty method to check it.
string b = null;
bool c = String.IsNullOrEmpty(b);
See this MSDN link for further details.
IsNullOrWhiteSpace(variableName)
string.IsNullOrEmpty()
var.Trim().Length < 1
The third one is the one I personally use, as it is version-independent.
I try to cast a variable type of Object int to a var.
My try is:
var dummy = (items[items.Count() - 1].GetType()) items[items.Count()-1];
I dunno what I'm doing wrong, i cant see my error, but the debugger says that only assign, decrement and "new Object"-expressions can be used as a command... But that's what I'm doing...
Can somebody show me my error?
Many thanks in advance, and sorry for that "beginnerquestion".
You need to use Convert.ChangeType
var obj = Convert.ChangeType(d, items[items.Count() - 1].GetType());
Casting is a compile type operation, you're telling the compiler: "This object is a [insert type here]". GetType() is a runtime method that returns a specific type (the type Type). So there are a couple of problems, you cannot use the runtime method in a compile time construct. Second, you would actually in this case be casting (assuming this was possible) to Type rather than say String (assuming GetType() returned String).
I'm not sure what you're trying to accomplish, but this is probably what you want to do: http://msdn.microsoft.com/en-us/library/dtb69x08.aspx
Also, I think you might not be understanding what var is (based on some of your comments). You "cast things to var", var is essentially a shortcut which allows the compiler to infer the type. So something like this:
var myString = "this is a test";
Is the equivalent of:
string myString = "this is a test";
Here's the source of the error you're experiencing.
Your compiler sees (items[items.Count() - 1].GetType()) as an expression, rather than a casting statement, so what it sees is
getAValue() (items[items.Count() - 1].GetType())
which doesn't make any sense.
you should cast your variable as others have said.
int number = 5;
Type dynamicType = number.GetType(); // dynamic type is "int"
dynamicType x = (number as dynamicType);
How would you expect the compiler to treat the variable x later in the code? It wouldn't know anything about it... so it couldn't resolve any method calls etc.
Basically what you're after is dynamic typing which is supported in C# 4 with the "dynamic" pseudo-type:
int number = 5;
dynamic d = number;
// Calls to d are resolved at execution time, so this compiles:
d.ThisWillThrowAtExecutionTime();
Type is an object that represents information about a type. It's not a designator for a variable saying it is of that type.
SomeObject myObject = new SomeObject();
Type t = myObject.GetType();
SomeObject myOtherObject = (SomeObject)Activator.CreateInstance(t);
The ability to do this goes all the way back to .Net v1.0. No need for fancy dynamic typing or anything like that.
Constructing objects with more complex constructors takes a bit more work, but it's the same idea.
You can, just not directly. You can use reflection. Basically you get the fully qualified name of the type (from the Type object) and then call CreateInstance method from an assembly object that contains that type. It should be quite simple to get the assembly reference of the current instance...
I think the Assembly.GetExecutingAssembly() method will do it.
I've written a little about this quite some time ago in a post at: http://frater.wordpress.com/2007/06/24/instantiating-classes-through-reflection-using-c-dynamic-object-creation/
That might help you out some more, though the focus was also on compiling of c# code from within a c# program, to allow for the use of C# as a scripting language, so some of the details might not be completely relevant.
Hope that helps!
Because it wouldn't make any sense.
What would you do next?
The purpose of a cast is to assign the casted object to a variable of the type that you casted it to. In this case, you wouldn't be able to do that, since a field must have a static type at compile time.
What are you trying to do?
dynamicType is an object of type "Type" that holds the Type meta-data information of type "int" hence dynamicType is and instance or object and not a qualified type so you cannot perform instantiation on that.
So, AFAIK you can't use the Type to instantiate 'basic' data types such as int.
You could use it to create objects though:
Object x=Activator.CreateInstance(dynamicType)
The issue is, if you want to call methods or access fields on a dynamic type, you have to use reflection. See the Type class documentation for instructions.