Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

I am trying to accomplish the following scenario that the generic TestClassWrapper will be able to access static properties of classes it is made of (they will all derive from TestClass). Something like:

public class TestClass
{
    public static int x = 5;
}

public class TestClassWrapper<T> where T : TestClass
{
    public int test()
    {
        return T.x;
    }
}

Gives the error:

'T' is a 'type parameter', which is not valid in the given context.

Any suggestions?

like image 319
gw0 Avatar asked Aug 25 '11 07:08

gw0


3 Answers

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

like image 119
Jon Skeet Avatar answered Nov 11 '22 03:11

Jon Skeet


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.

like image 23
cjk Avatar answered Nov 11 '22 04:11

cjk


Why not just return TestClass.x?

like image 3
Haris Hasan Avatar answered Nov 11 '22 05:11

Haris Hasan