user995689
user995689

Reputation: 825

Use string name to access class properties

How can I use a string variable to get the properties associated with a given class? If I use the class name as in the following:-

  PropertyInfo[] propertyInfo = typeof(Treblet).GetProperties();    

where Treblet is the class name then I can get the number of properties for the class. But how can I replace the name of the class with a string variable? Thanks for all and any help.

Upvotes: 1

Views: 195

Answers (2)

Kevin Holditch
Kevin Holditch

Reputation: 5303

string typeToSearchFor = "Treblet";
PropertyInfo[] propertyInfo = 
     Assembly.GetExecutingAssembly().GetTypes().Where(
         t => t.Name == typeToSearchFor).FirstOrDefault().GetProperties();

This should do the trick. You will need to search the assembly that the type is defined in. For simplicity I've just searched the executing assembly.

Note Name is just the name of the type and FullName is the name of the type fully namespaced.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

You need to take a step back - the problem isn't getting properties, it's getting a Type value on which to call GetProperties. For that, you want Assembly.GetType(string) or Type.GetType(string). In both cases you need the namespace-qualified name, e.g. System.Guid rather than just Guid.

If you use Type.GetType(string) with just a namespace-qualified name, it will only check in mscorlib and the calling assembly - you'll need an assembly-qualified name to find a type in a different assembly.

Upvotes: 1

Related Questions