skip to content

In C#, why do `MessageIds<Ping>.Id` and `MessageIds<Chat>.Id` read different values when the generic class declares a single static field?

level: middleimportance: should knowfreq 45%

answer

  1. open versus closed types
  2. each closed type is its own type
  3. static constructor runs per type
  4. class arguments behave the same

basics

~20 s

Each closed constructed type, such as MessageIds<Ping> or MessageIds<Chat>, is a separate type to the CLR with its own copy of every static field and its own static constructor run, so one declaration yields one value per type argument.

solid answer

~40 s

A generic class is an open type; `MessageIds<Ping>` and `MessageIds<Chat>` are two closed constructed types, and the CLR gives each its own static fields and runs each one's static constructor at most once, on first access. That holds for reference-type arguments too: code may be shared between them, but statics never are. The upside is a free per-type table, which is why a message bus can hand out one id per message type through `MessageIds<T>.Id`. The trap is shared state: a counter declared inside the generic class restarts at zero for every type argument, so a global counter must live in a non-generic holder, incremented with `Interlocked.Increment` because different closed types can initialize on different threads.

code

csharp · 27 lines
csharp
Console.WriteLine(MessageIds<Ping>.Id);
Console.WriteLine(MessageIds<Chat>.Id);
Console.WriteLine(MessageIds<Ping>.Id);
Console.WriteLine(MessageIds<Move>.Id);
Console.WriteLine($"naive: {NaiveIds<Ping>.Id} {NaiveIds<Chat>.Id} {NaiveIds<Move>.Id}");

static class IdSource
{
    private static int _next;
    internal static int Next() => Interlocked.Increment(ref _next);
}

static class MessageIds<T>
{
    public static readonly int Id = IdSource.Next();
    static MessageIds() => Console.WriteLine($"static constructor: MessageIds<{typeof(T).Name}>");
}

static class NaiveIds<T>
{
    private static int _next;              // one counter per closed type, not one in all
    public static readonly int Id = ++_next;
}

record Ping;
record Chat;
record struct Move(int X, int Y);

go deeper

for a junior

Remember that MessageIds<Ping> and MessageIds<Chat> are different types, so each has its own statics and its own static constructor run.

for a middle

Explain open versus closed types, show the initialization order with a static constructor, and stress that class arguments get separate statics even when the runtime shares their code.

for a senior

Spot the naive per-type counter in review, move shared state to a non-generic holder with Interlocked, and remember that a throwing initializer disables only that closed type.

for a principal

Weigh per-type statics as hidden global state: they live as long as the process, cannot be reset between tests, and CA1000 flags them on public generic types.

## Open types, closed types and where statics live A generic class declaration such as `static class MessageIds<T>` is an **open type** (a generic type definition): it describes a family of types but cannot hold data itself. Supplying a type argument produces a **closed constructed type**, such as `MessageIds<Ping>` or `MessageIds<Move>`. To the CLR, every closed constructed type is a **separate type** with its own identity and, crucially, its own copy of every **static field**. So a single `static` declaration in source becomes as many storage locations as there are closed types the program touches. In the scenario of a game server's message bus, where each message type gets its own `MessageChannel<TMessage>` and needs a stable numeric id for the wire, that is exactly what you want: `MessageIds<Ping>.Id` and `MessageIds<Chat>.Id` are two different fields. ## What runs once per closed type The snippet in this question shows the sequence, step by step: 1. The first read of `MessageIds<Ping>.Id` triggers the **type initializer** of the closed type `MessageIds<Ping>`: its static constructor runs, and the field initializer calls the shared `IdSource.Next()`, which returns `1`. 2. The first read of `MessageIds<Chat>.Id` is a first access to a **different** type, so a second static constructor run happens and that type's field gets `2`. 3. Reading `MessageIds<Ping>.Id` again touches an already initialized type: no constructor runs and the stored `1` comes back. 4. `MessageIds<Move>` (a struct argument) is a third closed type and gets `3`. The C# programming guide's rule for static constructors applies per type: the runtime calls one "no more than once in a single application domain", inside a lock taken for that specific type, so concurrent first accesses from several threads still see one initialization per closed type. | Member of `MessageIds<T>` | How many copies | |---|---| | `static` field | one per closed constructed type | | static constructor | runs at most once per closed constructed type | | instance field | one per object, as usual | | `const` | a compile-time constant, nothing stored per type | | static field of a nested class `MessageIds<T>.Cache` | one per closed type too, because the nested class is implicitly generic over `T` | ## Reference-type arguments are no exception A common guess is that `MessageIds<Ping>` and `MessageIds<Chat>` must share their statics because both arguments are classes and the runtime shares one compiled body for reference-type instantiations. The code may be shared, but the **statics are not**: `Ping` and `Chat` above are both `record` classes, and they print different ids. How the JIT shares code for reference types belongs to the runtime material; the language-level rule is simply one set of statics per closed type. ## The classic bug: a counter meant to be global `NaiveIds<T>` declares its counter inside the generic class. Each closed type gets its own `_next`, each starts at `0`, and every message type receives id `1`. The fix is to keep **shared state outside the generic type**: - put the counter in a **non-generic** holder, as `IdSource` does, and let the generic class read from it; - or put shared statics on a **non-generic base class**; statics declared on a closed base such as `Base<int>` are shared by every class deriving from that same `Base<int>`, but not with `Base<string>`; - use `Interlocked.Increment` on the shared counter, because two closed types can initialize on two threads at once and each type's lock does not protect the other's. ## Design notes and diagnostics - **Call-site syntax.** A static member of a generic type is always reached through a closed type, `MessageIds<Ping>.Id`; nothing can be inferred there. The code-analysis rule **CA1000**, "Do not declare static members on generic types", flags this for externally visible types because callers must write the type argument; it is not enabled by default in .NET 10, and it does not look at internal types unless configured. - **Lifetime.** Each closed type's statics live for the lifetime of the process (more precisely, of the load context that holds the type), so a static collection inside a generic type grows once per closed type and is never released. - **Initialization failures are per type.** If the initializer of `MessageIds<Secret>` throws, that one closed type is left unusable while the other closed types keep working. ## Summary Statics on a generic type are keyed by the full closed type. That makes `MessageIds<T>` a free "one value per type" table, and it makes a counter declared inside the generic type count once per type argument rather than once overall.

  • Two classes derive from `Base<int>`, which declares a static field. Do they share it?
    Yes. The static belongs to the closed type `Base<int>`, not to each derived class, so `Derived1` and `Derived2` both read and write the same field. A third class deriving from `Base<string>` gets a separate field, because `Base<string>` is a different closed type.
  • Is a static constructor on a generic type thread-safe for initialization?
    Yes, per closed type. The runtime runs a type's static constructor at most once, inside a lock for that type, so two threads touching `MessageIds<Ping>` first see one initialization. The locks are per type, though: `MessageIds<Ping>` and `MessageIds<Chat>` can initialize in parallel, so any state they share needs its own synchronization, such as `Interlocked.Increment`.

  • a static field on a generic class is shared by all type arguments
  • only value-type arguments get their own static fields
  • the static constructor runs once for the generic definition
  • the open type List<> holds its own static data
  • a counter inside the generic class counts across all T