Skip to content

Static Fields in Generic Types

Question

Is there any difference in a static field inside a generic class in contrast to class?

Short interview answer

A static field in a generic type is separate for each closed constructed type. Cache<int>.Count and Cache<string>.Count are different static fields; a static field in a non-generic type has one field for that type.

Detailed answer

Cache<T> is a type definition, but Cache<int> and Cache<string> are distinct constructed types at runtime:

public static class Cache<T>
{
    public static int Count;
}

Cache<int>.Count++;
Console.WriteLine(Cache<int>.Count);    // 1
Console.WriteLine(Cache<string>.Count); // 0

This is useful for per-type caches, but it surprises developers expecting one application-wide counter. If one value must be shared regardless of T, put it in a non-generic type instead.

Sources