Tuesday, 1 July 2008

Accessing static properties using C# reflections

Using C# reflections is quite easy. I found some good examples here. However, most of the examples available on the Web do not cover static class members. In order to access a static class member you don't need to use Activator since you don't need the class instance. Here is a simple example for accessing static property:
//Get type of MyClass
Type myType = Type.GetType("MyNamespace.MyClass");

//Get PropertyInfo for property SomeProperty
PropertyInfo pi = myType.GetProperty("SomeProperty");

//Display property value on console.
//Because it's static you can pass nulls for both object and index
Console.WriteLine("Value of my property is: " +
pi.GetValue(null, null));