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)
    if (!type.IsSubclassOf(typeof(MyBaseClass)))
    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.

%d bloggers like this: