Static fields and generics
I'm trying to find a way to create a generic base class which contains static members which are 'global' to all typed subclasses. For example if I create the following class.
public class GenericTest<T>
{
private static string test = null;
public string Test
{
get
{
if(test == null){ test = typeof(T).Name; }
return test;
}
}
}
...and then from a main method call
GenericTest<string> obj1 = new GenericTest<string>();
GenericTest<int> obj2 = new GenericTest<int>();
Console.WriteLine(obj1.Test);
Console.WriteLine(obj2.Test);
Gives the output:
String
Int32
What I'm trying to figure out is a way to get the test to output:
String
String
i.e: I want the static field "test" to be defined only once, rather than multiple times for each paramaterised version of class "GenericTest".
I know I can do this by creating a static class that contains the global static state for all "GenericTest" types but I would rather avoid this as I'm keen to keep all code neatly encapsulated.
Also using inheritence to declare a base non-genric class is not an option in my current position.
Does anybody know if this is possible?
Thanks in advance for any replies.
Oh yeah, I'm using .Net 2.0

