C# Static variables of FooBar<T> are per T
I discovered a comment about a thir of the way down Eric Lippert's recent blog entry, where he asked people to share their experiences of discovering something non-intuitive about programming languags:
class Program
{
static void Main(string[] args)
{
int intGenericClassId = GenericClass<int>.GetId();
int boolGenericClassId = GenericClass<bool>.GetId();
print(typeof(GenericClass<int>).Name, intGenericClassId);
print(typeof(GenericClass<bool>).Name, boolGenericClassId);
GenericClass<int>.SetId(3);
Console.WriteLine("Set <GenericClass<int> to Id of 3");
intGenericClassId = GenericClass<int>.GetId();
boolGenericClassId = GenericClass<bool>.GetId();
print(typeof(GenericClass<int>).Name, intGenericClassId);
print(typeof(GenericClass<bool>).Name, boolGenericClassId);
Console.ReadKey();
}
private static void print(string typeName, int value)
{
Console.WriteLine("Starting value of Int for {0}: {1}", typeName, value);
}
internal static class GenericClass<T> where T : struct
{
private static int _id = 0;
static GenericClass()
{
}
public static int GetId()
{
return _id;
}
public static void SetId(int value)
{
_id = value;
}
}
}
Discovering that the static variables of generic type Foo<t> were per T was interesting (and I see why they are that way) just that it was quite subtle when I first hit it.What would you know, it's true:
class Program
{
static void Main(string[] args)
{
int intGenericClassId = GenericClass<int>.GetId();
int boolGenericClassId = GenericClass<bool>.GetId();
print(typeof(GenericClass<int>).Name, intGenericClassId);
print(typeof(GenericClass<bool>).Name, boolGenericClassId);
GenericClass<int>.SetId(3);
Console.WriteLine("Set <GenericClass<int> to Id of 3");
intGenericClassId = GenericClass<int>.GetId();
boolGenericClassId = GenericClass<bool>.GetId();
print(typeof(GenericClass<int>).Name, intGenericClassId);
print(typeof(GenericClass<bool>).Name, boolGenericClassId);
Console.ReadKey();
}
private static void print(string typeName, int value)
{
Console.WriteLine("Starting value of Int for {0}: {1}", typeName, value);
}
internal static class GenericClass<T> where T : struct
{
private static int _id = 0;
static GenericClass()
{
}
public static int GetId()
{
return _id;
}
public static void SetId(int value)
{
_id = value;
}
}
}
