C# accessing a static property of type T in a generic class

You can't, basically, at least not without reflection.

One option is to put a delegate in your constructor so that whoever creates an instance can specify how to get at it:

var wrapper = new TestClassWrapper<TestClass>(() => TestClass.x);

You could do it with reflection if necessary:

public class TestClassWrapper<T> where T : TestClass
{
    private static readonly FieldInfo field = typeof(T).GetField("x");

    public int test()
    {
        return (int) field.GetValue(null);
    }
}

(Add appropriate binding flags if necessary.)

This isn't great, but at least you only need to look up the field once...


Surely you can just write this:

public int test() 
{ 
    return TestClass.x; 
} 

Even in a nontrivial example, you can't override a static field so will always call it from your known base class.

Tags:

C#