Suppose I have two classes that both contain a static variable, XmlTag. The second class inherits from the first class. I have a template method that needs to obtain the XmlTag depending on the which type it is using. What would be the best way to accomplish this, without having to create an instance of the type? Here is an example(that won’t compile), that should hopefully illustrate what I’m talking about.
class A{
public static readonly string XmlTag = "AClass";
}
class B : A {
public static readonly string XmlTag = "BClass";
}
This method is currently invalid.. Static variables can’t be accessed from Type paramaters apparently.
string GetName<T>(T AClass) where T : A
{
return T.XmlTag;
}
First off, stop thinking of generic methods as templates. They are NOT templates. They have very different behaviour from templates; your expectation that they behave like templates is possibly what is leading you astray in this situation.
Here is a series of articles I wrote about your scenario and why it is illegal.
http://blogs.msdn.com/ericlippert/archive/2007/06/14/calling-static-methods-on-type-variables-is-illegal-part-one.aspx
http://blogs.msdn.com/ericlippert/archive/2007/06/18/calling-static-methods-on-type-variables-is-illegal-part-two.aspx
http://blogs.msdn.com/ericlippert/archive/2007/06/21/calling-static-methods-on-type-variables-is-illegal-part-three.aspx
Note that of course the “dynamic” feature that I hint at in part three is in fact shipping with C# 4.0.
To address your actual question: “what’s the best way to do this?” Presumably you have some problem which you believe a mechanism like this would solve. This mechanism doesn’t actually exist in C#. It is impossible for us to deduce what problem you are actually trying to solve from the fact that you would like this mechanism to exist. Instead of asking “how can I make this impossible thing work in C#?” instead describe the real problem you have, and we can take a crack at trying to come up with an existing C# mechanism that better solves your real problem.