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));

2 comments:

Anonymous said...

May be a little explanation - where you defined static property ??

Filip Czaja said...

The static property "SomeProperty" is defined in class MyNamespace.MyClass. If no reflections required it could be accessed like this:
MyNamespace.MyClass.SomeProperty