We all know that a static variable will be shared by entire class instead of objects. What about Generic Types?? Suppose, from a generic type, if 2 constructed types created, will they maintain different copy or same copy?? They will maintain their own copy.
class A<T> { static int M; public static void addnum() { M++; Console.WriteLine(M); } } class C { public static void Main() { A<int> a = new A<int>(); A<int>.addnum(); A<int> a2 = new A<int>(); A<int>.addnum(); A<string> a3 = new A<string>(); A<string>.addnum(); Console.ReadKey(); } }
Don't be confused... Constructed Types are classes only, where as Generic Types are like templates. Static variable will be maintained in class level. So, constructed types will maintain their own copy.
Published under: Microsoft .NET Tips · · · ·