Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Reflection to get the value of a Static Property of a Type without a concrete instance

Consider the following class:

public class AClass : ISomeInterface
{
    public static int AProperty
    {
   get { return 100; } 
    }
}

I then have another class as follows:

public class AnotherClass<T>
   where T : ISomeInterface
{

}

Which I instance via:

AnotherClass<AClass> genericClass = new  AnotherClass<AClass>();

How can I get the static value of AClass.AProperty from within my genericClass without having a concrete instance of AClass?

like image 494
Stewart Alan Avatar asked Jun 22 '12 14:06

Stewart Alan


People also ask

How does reflection set property value?

To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.

Which type of properties can be referenced without creating an instance of the class?

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.


1 Answers

Something like

typeof(AClass).GetProperty("AProperty").GetValue(null, null)

will do. Don't forget to cast to int.

Documentation link: http://msdn.microsoft.com/en-us/library/b05d59ty.aspx (they've got example with static properties, too.) But if you know exactly AClass, you can use just AClass.AProperty.

If you are inside AnotherClass<T> for T = AClass, you can refer to it as T:

typeof(T).GetProperty("AProperty").GetValue(null, null)

This will work if you know for sure that your T has static property AProperty. If there is no guarantee that such property exists on any T, you need to check the return values/exceptions on the way.

If only AClass is interesting for you, you can use something like

if (typeof(T) == typeof(AClass))
    n = AClass.AProperty;
else
    ???
like image 118
Vlad Avatar answered Nov 15 '22 15:11

Vlad