Although this topic is quite common, but still I see folks getting confused here and there about the behavior of having a static
members in the generic type.
Today, I saw another question on stackoverflow about the same. So I thought I shall write a small blog post about the same.
Normally, we know that static
members are unique for a type no matter how many instances you create of that type. But this concept behaves a bit differently in generics. If you have read the C# spec, then you would have figured out by now. It states the some thing like this “For every open type T
, the type having static
members maintains the common/unique value”.
Let me show you a sample code for explanation:
public class Base
{
public static string str = null;
static Base()
{
str = "hello";
Console.WriteLine("Ctor cald");
}
}
As you can see in the above code, the static
member by virtue of its nature stays common/unique for this type Base no matter how many derived/base instances are created, right. Yep.
But as soon as you introduce generics to this code, things starts to behave a bit differently. As already stated above, for each open type T
(in below code), the base type holds a common static
member in it.
Let me show you a sample code for the same:
public class Base < T >
{
public static string str = null;
static Base()
{
str = "hello";
Console.WriteLine("Ctor cald");
}
}
public class Derived1 < T > : Base < T > { }
public class Derived2 < T > : Base < T > { }
public class Program
{
public static void Main()
{
Derived1 < int > derv = new Derived1 < int >();
Derived2 < double > derv2 = new Derived2() < double >;
Derived2 < double > derv3 = new Derived2() < double >;
Console.ReadKey();
}
}
So how many times the static
ctor in the above code would be called? 3? No, wrong. In this case, it's only 2 times. Because for every open type T
you pass (in this case, int
and double
types in main
method), the base types static
members are maintained unique for that open type T
.
If you supposedly run FxCop on your generic type code having static
members, you would get this warning. So be careful in using static
in generics.
Hope it helps. Thanks for reading.
Your comments/votes are always appreciated.
Happy coding.
Filed under:
C#,
CodeProject,
Dotnet Tagged:
.NET,
blog,
C#,
codeproject,
Dotnet,
generic type,
static members,
tips