How do generic type parameters interact with static members, and why does each closed generic type get its OWN independent set of static field values?
Short answer
Unlike instance members, STATIC fields on a generic class are NOT shared across different closed generic instantiations — Box and Box each get their OWN, completely independent copy of any static field declared in Box , since the CLR generates a distinct type for each unique…
Advertisement
AModel answer
Unlike instance members, STATIC fields on a generic class are NOT shared across different closed generic instantiations — Box<int> and Box<string> each get their OWN, completely independent copy of any static field declared in Box<T>, since the CLR generates a distinct type for each unique combination of generic arguments (for reference types sharing code, but with separate static storage).
public class Counter<T> {
public static int InstanceCount = 0;
public Counter() { InstanceCount++; }
}
new Counter<int>(); new Counter<int>();
new Counter<string>();
Console.WriteLine(Counter<int>.InstanceCount); // 2
Console.WriteLine(Counter<string>.InstanceCount); // 1 -- separate, independent counter!Real-world example
Debugging a surprising bug where a 'shared' static counter on a generic class turned out to be tracking each closed generic type SEPARATELY, not globally.
Likely follow-ups
- Why does the CLR handle this differently for VALUE TYPE versus REFERENCE TYPE generic instantiations, in terms of code generation?
Related topics