Static data is not shared among constructed generic types.
That is, the final line of output from the following program:
using System; class Program { static void Main() { NonGeneric.PrintCount(); // "Called 1 time." NonGeneric.PrintCount(); // "Called 2 times." Generic<int>.PrintCount(); // "Called 1 time." Generic<string>.PrintCount(); // ? } public static void DoPrintCount(int count) { Console.WriteLine("Called {0} time{1}.", count, count > 1 ? "s" : ""); } } class NonGeneric { public static void PrintCount() { Program.DoPrintCount(++count); } static int count; } class Generic<T> { public static void PrintCount() { Program.DoPrintCount(++count); } static int count; }
Is “Called 1 time.”
The statement “Static data is not shared among constructed generic types.” is incomplete. It should read something like “Static data is not shared amongst instances of unique constructed generic types.” since the following is true
Generic.PrintCount(); // “Called 1 time.”
Generic.PrintCount(); // “Called 2 time.”
Comment by Scott — July 21, 2008 @ 5:14 pm
oops, i meant to include the generic int type argument
Generic<int>.PrintCount(); // “Called 1 time.”
Generic<int>.PrintCount(); // “Called 2 time.”
Comment by Scott — July 21, 2008 @ 5:15 pm
This is actually a great feature. It’s the reason why EqualityComparer.Default works.
Comment by Dustin Campbell — July 22, 2008 @ 6:30 am
Yeah; it totally makes sense why it’s the case. (Consider a static field of type
T… that couldn’t possibly be shared among constructed types.) I just had sort of forgotten that it was the case.Comment by Jacob — July 22, 2008 @ 7:07 am
Yeah, it enables fun stuff like this:
http://www.codeplex.com/DynamicGeometry/SourceControl/FileView.aspx?itemId=154936&changeSetId=12000
Comment by Kirill Osenkov — July 24, 2008 @ 11:48 pm