tags:

views:

433

answers:

2

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
     }
    }
+17  A: 

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.

Jon Skeet
+1 Too fast! :)
Andrew Hare
+1 for actually reading the question :)
Yohnny
With the details posted it would seem over kill since he can just reference MyClass.StaticMemberIt only really matters if myObject could be more than one Class and you can't know which at development.
Robert
@Robert: That's exactly his situation though. See the comments to the question.
Jon Skeet
Sorry it's taken me so long to thank you, but I've been working on getting your ideas to work in my case. Thanks, Jon, and everyone!
JaysonFix
+5  A: 

If you have control of MyClass and need to do this often, I'd add a member property that gives you access.

Lou Franco