C# -- how does one access a class' static member, given an instance of that class?

JaysonFix picture JaysonFix · Jul 14, 2009 · Viewed 11.4k times · Source

In C#, suppose you have an object (say, myObject) that is an instance of class MyClass. Using myObject only, how would you access a static member of MyClass?

class MyClass
    {
    public static int i = 123 ;
    }

class MainClass
    {
    public static void Main()
        {
        MyClass myObject = new MyClass() ;
        myObject.GetType().i = 456 ; //  something like this is desired,
                         //  but erroneous
        }
    }

Answer

Jon Skeet picture Jon Skeet · Jul 14, 2009

You'd have to use reflection:

Type type = myObject.GetType();
FieldInfo field = type.GetField("i", BindingFlags.Public |
                                     BindingFlags.Static);
int value = (int) field.GetValue(null);

I'd generally try to avoid doing this though... it's very brittle. Here's an alternative using normal inheritance:

public class MyClass
{
    public virtual int Value { get { return 10; } }
}

public class MyOtherClass : MyClass
{
    public override int Value { get { return 20; } }
}

etc.

Then you can just use myObject.Value to get the right value.