🔧 Fix a Static Constructor Deadlocking on Its Own Type
The CLR guarantees a type’s static constructor runs exactly once before the type is first used, enforcing this with an internal per-type lock held for the constructor’s entire duration. If that static constructor’s body — directly, or through a method it calls — triggers any code path that tries to access a static member of the SAME type again before the constructor finishes, the CLR detects it’s back on the same thread re-entering the same lock, and the result is either a wrapped `TypeInitializationException`, or, on a genuinely different thread blocked rather than re-entering, a true deadlock where that thread waits forever for initialization that’s itself waiting on something only that thread could finish.
🔎 The Problem
static class Config
{
private static readonly Dictionary<string, string> _values = LoadValues();
private static Dictionary<string, string> LoadValues()
{
// BuildDefault() reads Config.Fallback, a static field on this SAME
// type, while the static constructor is still initializing it -
// re-entrant access throws or deadlocks depending on the thread
return BuildDefault(Config.Fallback);
}
public static readonly string Fallback = "default";
}
✅ Fix: Keep the Constructor Thin
- Keep static constructors minimal and side-effect-free wherever possible — assign simple values, and defer any expensive or cross-cutting initialization to an explicit `Initialize()` method called deliberately at startup, not implicitly from the type-initialization path.
- If a static constructor must call another method, trace every call it makes for any path that loops back to the SAME type’s static members, especially through a shared static field the constructor and the called method both touch — that self-reference is the direct cause of the re-entrancy.
- For lazy, thread-safe static state that needs more control than a static constructor gives you — including the ability to retry after a failed first attempt, which a throwing static constructor permanently poisons — use `Lazy<T>` with an explicit thread-safety mode instead.
🚨 Why This Is Dangerous
- A `TypeInitializationException` thrown from a re-entrant static constructor permanently marks that type as unusable for the rest of the process’s lifetime — every later attempt to use it, from completely unrelated code, throws the same cached exception again.
The CLR’s one-time guarantee for a static constructor is also a one-time chance – fail it once and the type stays broken for the rest of the process.

