Using Reflection for retrieving values of static properties

I had a list of classes for which I wanted to retrieve the static property Description; this is how I found out it can be done using Reflection:

Assembly assembly = Assembly.GetExecutingAssembly();
var types = assembly.GetTypes();
foreach (var type in types)
{
    if (!type.IsClass)
        continue;
    if (!type.IsSubclassOf(typeof(MyBaseClass)))
        continue;
    object obj = Activator.CreateInstance(type, new object[] { 0, 0 });
    PropertyInfo pi = obj.GetType().GetProperty("Description");
    string propValue = pi.GetValue(null, null).ToString();
}

Note:If Description is a property of the base class MyBaseClass, you’ll have to use obj.GetType().BaseType.GetProperty(“Description”); for this to work.
Also, as you can see, at least in my case, I need to create instances of the classes I work with, because Description property is defined in a base class, not in the derived ones, and the static property will be populated via constructors.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: