How does a C# static generic class such as `Codec<T>` act as a per-type cache without a `Dictionary<Type, T>`, and where does that idiom bite in production?
answer
- statics keyed by closed type
- initializer runs once under a lock
- how Array.Empty<T> is built
- failures are remembered too
- no Type object, no eviction
basics
~20 sEach closed type such as Codec<Ping> has its own static field, initialized once under the runtime's per-type lock, so a lookup is a static field read. The costs: a throwing initializer stays broken, entries never evict, and the type must be a type argument.
solid answer
~40 sA `static readonly` field on `Codec<T>` is stored per closed constructed type, and the runtime runs each closed type's initializer once, under a lock taken for that type. So `Codec<Ping>.Instance` is built on first access and afterwards read as an ordinary static field, with no hashing and no locking; `Array.Empty<T>()` uses the same trick through a nested `EmptyArray<T>`. It bites in four places: a throwing initializer is never retried, so every later access throws `TypeInitializationException`; entries live as long as the process and cannot be evicted or reset for tests; the cache only works when the type is a type argument, not a `Type` value; and blocking inside the initializer risks a deadlock. Use a `ConcurrentDictionary<Type, TValue>` when those matter.
code
csharp · 27 linesConsole.WriteLine(Codec<Ping>.Instance.Describe());
for (int i = 0; i < 2; i++)
{
try { Console.WriteLine(Codec<Secret>.Instance.Describe()); }
catch (TypeInitializationException ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.InnerException?.GetType().Name}"); }
}
Console.WriteLine(Codec<Chat>.Instance.Describe());
static class Codec<T>
{
public static readonly PacketCodec Instance = PacketCodec.Build(typeof(T));
}
sealed class PacketCodec(string name)
{
public static PacketCodec Build(Type type)
{
Console.WriteLine($"building codec for {type.Name}");
if (type == typeof(Secret)) throw new NotSupportedException();
return new PacketCodec(type.Name);
}
public string Describe() => $"codec:{name}";
}
record Ping;
record Chat;
record Secret;go deeper
Know that each Codec<Ping>, Codec<Chat> has its own static field, so a static generic class can store one value per type.
Explain why the read path needs no lock: the runtime initializes each closed type once under its own lock, and later reads are plain field loads.
Name the production failure modes: TypeInitializationException pinned after one bad initialization, no eviction, deadlocks from blocking initializers, and no access from a runtime Type.
Decide where the idiom is allowed: deterministic, cheap-to-describe values in internal types, with a dictionary or managed cache for anything evictable or configuration-driven.
## The idiom C# gives every **closed constructed type** its own static fields, and the runtime runs each closed type's **type initializer** at most once. Put those two rules together and a static generic class becomes a cache keyed by type, with no dictionary in sight: ```csharp static class Codec<T> { public static readonly PacketCodec Instance = PacketCodec.Build(typeof(T)); } ``` On a game server's message bus, `Codec<Ping>.Instance` and `Codec<Chat>.Instance` are two different fields. The first access to each runs `PacketCodec.Build` once for that type; every later access is a plain read of an already initialized static field. The base class library uses the same shape: `Array.Empty<T>()` simply returns `EmptyArray<T>.Value`, a `static readonly T[]` held by a private nested `EmptyArray<T>` class, so each element type gets exactly one shared empty array. ## What it buys over `Dictionary<Type, TValue>` | | `Codec<T>.Instance` | `ConcurrentDictionary<Type, PacketCodec>` | |---|---|---| | Key | the closed type itself, resolved when the code is compiled for that `T` | a `System.Type` object hashed on each lookup | | Lookup after the first | a static field read | a hash and a bucket search per call | | First-time creation | exactly once per closed type, under the runtime's per-type lock | `GetOrAdd` may invoke its value factory more than once under contention | | Works with a runtime `Type` value | no, the type must be a type argument | yes | | Eviction or reset | none | `TryRemove`, `Clear` | Three properties make it attractive in hot paths: - **No hashing and no lock on the read path.** Once initialized, the access is a field load on the closed type. - **Thread-safe creation for free.** The C# programming guide states that the runtime calls a static constructor "no more than once in a single application domain", in "a locked region based on the specific type of the class", so no extra locking is needed inside the initializer. - **Type-safe values.** `Codec<T>` can expose a `Func<T, byte[]>` or a `PacketCodec<T>` typed to `T`, where a dictionary keyed by `Type` has to store `object` or a non-generic base and cast on the way out. ## Where it bites 1. **A failed initializer is cached too.** If `PacketCodec.Build` throws for `Secret`, the runtime does not retry: in the snippet the second access throws **`TypeInitializationException`** again, wrapping the original `NotSupportedException` as `InnerException`, and "building codec for Secret" is printed only once. The programming guide says the type "remains uninitialized for the lifetime of the application domain". A transient failure, such as a configuration file that was not readable yet, becomes permanent until the process restarts. Keep initializers deterministic, or store a lazily retried value instead of computing it in the initializer. 2. **No eviction, no reset.** Each closed type's statics live as long as the process (strictly, as long as the load context holding the type), so a cache that holds large per-type data grows with the number of type arguments ever used and cannot be cleared. Unit tests that need a fresh state cannot get one. 3. **The type must be a type argument.** `Codec<T>` works inside another generic method, where `T` is the caller's type parameter, but not when all you have is a `Type` object from configuration or deserialization. Bridging from a `Type` to `Codec<T>` needs reflection, which brings its own cost and trimming concerns, or a dictionary in front. 4. **Blocking in an initializer can deadlock.** Because initialization runs under a per-type lock, the guide warns not to wait on tasks, threads or wait handles, take locks, or run blocking parallel loops inside static constructors and initializers. Two closed types whose initializers wait on each other from two threads can hang. 5. **Timing is less precise without a static constructor.** A class with only field initializers is emitted with the `BeforeFieldInit` attribute; the guide notes that adding an explicit static constructor "prevents the addition of the BeforeFieldInit type attribute" and that this "limits runtime optimization". Declare one only when the exact moment of initialization matters. 6. **Public exposure trips CA1000.** The analyzer rule "Do not declare static members on generic types" flags static members on externally visible generic types; cache holders are normally `internal` or private nested types, which the rule ignores by default. ## When to choose it Use a static generic cache when the set of types is open, the value is cheap to describe but expensive to build (a serializer, a precomputed size, a comparer, an empty instance), the build cannot fail transiently, and callers always have the type as a type argument. Prefer a `ConcurrentDictionary<Type, TValue>` or an explicitly managed cache when keys arrive as `Type` values at run time, entries must be evictable, or initialization talks to the outside world.
- Your codec cache must also serve types that arrive as `Type` values from a config file. What changes?A static generic class can only be reached with a type argument, so a `Type` value needs a bridge: a `ConcurrentDictionary<Type, PacketCodec>` that callers with a runtime `Type` use, possibly filled from `Codec<T>` by callers that do know `T`, or reflection to close the generic type, which adds cost and trimming concerns. Many codebases keep both paths.
- How do you stop one transient failure from disabling a type's cache entry for good?Do not let the type initializer do work that can fail transiently. Store a `Lazy<T>` created with `LazyThreadSafetyMode.PublicationOnly`, which re-runs its factory when no attempt has succeeded, or a nullable field filled by an explicit `TryGet` method that can be retried, so a failed build is attempted again on the next call instead of being pinned as a `TypeInitializationException`.
- a static generic cache needs a lock on every read
- a failing initializer is simply retried on the next access
- Codec<T> can be looked up from any System.Type value directly
- per-type statics can be cleared like a dictionary
- Ping and Chat share one entry because both are classes