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
}
}
You simply have to use:
MyClass.i
To elaborate a little, in order to use a static member, you have to know about the class. And having an object reference is irrelevant. The only way an object would matter is when you would have 2 distinct classes that both have an identical looking member:
But
A.i
andB.i
are completely different fields, there is no logical relation between them. Even if B inherits from A or vice versa.If you have control of MyClass and need to do this often, I'd add a member property that gives you access.
You'd have to use reflection:
I'd generally try to avoid doing this though... it's very brittle. Here's an alternative using normal inheritance:
etc.
Then you can just use
myObject.Value
to get the right value.