Monday, June 23, 2008

 

Statics and Generics

If you think about it, it makes total sense. But, this is something you need to be careful of if you are use static member variables inside of generic classes. Basically, each different type you pass into a generic creates a new class, and each of those classes has its own set of static member variables!

As an example, consider the following trivial example class.


class MyGenericClass<T>
{
private static int s_IdCounter = 0;

private int _id;

private T _value;

public MyGenericClass(T value)
{
_id = Interlocked.Increment(ref s_IdCounter);
_value = T;
}

public int Id
{
get
{
return _id;
}
}

public T Value
{
get
{
return _value;
}
}
}

 

Now, consider what happens to the Id property when you create the following instances.


MyGenericClass<object> obj1 = new MyGenericClass<object>(null);
MyGenericClass<object> obj2 = new MyGenericClass<object>(null);
MyGenericClass<string> obj3 = new MyGenericClass<string>(null);
 

The actual values of the Id properties for those objects are.


obj1.Id == 1
obj2.Id == 2
obj3.Id == 1
 

The reason this occurs is because obj1 and obj2 are of the same type (MyGenericClass<object>) whereas obj3 is actually of a different type (MyGenericClass<string>). If you truely need them to share the same set of static member variables, then you need another class that contains the statics. You can either derive your generic from that other class, or you can have the generic use that other class. I personally prefer the later because I feel that a class intended to only hold static member variables should be a static class, but the compiler will not let you derive a non-static class from a static class.

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]