Stewart Alan
Stewart Alan

Reputation: 1643

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?

Upvotes: 9

Views: 4740

Answers (3)

Vlad
Vlad

Reputation: 35584

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
    ???

Upvotes: 11

brunoss
brunoss

Reputation: 31

Be sure you're binding the flags you want http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156459

First get the generic type of your AnotherClass instance.

Then get the static property.

Then get the property's static value.

// I made this sealed to ensure that `this.GetType()` will always be a generic
// type of `AnotherClass<>`.
public sealed class AnotherClass<T>
{
    public AnotherClass(){
        var aPropertyValue = ((PropertyInfo)
                this.GetType()
                    .GetGenericArguments()[0]
                    .GetMember("AProperty")[0])
            .GetValue(null, null);
    }
}

Recognizing, of course, that it isn't possible to ensure that "AProperty" will exist, because interfaces don't work on static signatures, I removed ISomeInterface as being irrelevant to the solution.

Upvotes: 1

Related Questions