views:

90

answers:

3

I'm using reflection to get the properties of an object and there's no difficulty in that but I need to make my class even more generic so basically what I'm trying to do is the following:

PropertyInfo[] properties = (typeof ("ObjectName")).GetProperties(BindingFlags.Public | BindingFlags.Instance);

Or something similar. Notice the use of a string inside the typeof. I know this doesn't work, this is just to show what I'm trying to accomplish. I've also tried:

public void Test(object myObject)  
{  
    typeof(myObject.GetType());  

    Type myType = myObject.GetType();
    typeof(myType);
}

with no success.

+3  A: 

Sounds like you may want Type.GetType or Assembly.GetType. One caveat with the former - unless the type is in the calling assembly or mscorlib, you need to give the assembly name as well as the type name - see this question from earlier today for an example.

Alternatively, in your example code you've got myObject.GetType() - doesn't that really do everything you want? It's not clear exactly what you're trying to achieve here.

Jon Skeet
I agree that you should be able to use myObject.GetType().GetProperties( ... ).
tvanfosson
+1  A: 

If you just want to get the Type of the object in question, use the object.GetType() method, like this:

Type myType = myObject.GetType();

PropertyInfo[] properties = myType.GetProperties(
    BindingFlags.Public | BindingFlags.Instance);

This assumes that you have an instance of the type already, but that you don't know what the type would be at compile time, or that it could be any type.

Drew Noakes
A: 

You want the static Type.GetType method. For example:

Type t=Type.GetType("System.String");
Sean