🔧 Your Static Constructor Isn’t Running When You Think It Is
A static constructor looks like it should run once, at program start, the way a regular constructor runs when you say `new` – but the runtime actually defers it until just before the type is first touched, which means the timing (and the exceptions it can throw) depends on code you may not control.
🔎 The Problem
public static class Config
{
public static readonly string ConnectionString;
static Config()
{
Console.WriteLine("Loading config...");
ConnectionString = File.ReadAllText("connstring.txt");
}
}
// "Loading config..." doesn't print at app startup -
// it prints the FIRST time any member of Config is accessed,
// which could be seconds or minutes into the program's life.
Console.WriteLine("App started");
var cs = Config.ConnectionString; // <- static ctor actually runs HERE
✅ Why the Timing Is Lazy by Design
- The CLR guarantees a type’s static constructor runs exactly once, and no later than the first access to any static member or the first instance created – but it does NOT guarantee it runs at process start, so ‘before main()’ is not a safe assumption.
- This laziness is usually a performance feature – types you never touch never pay their static initialization cost – but it becomes a surprise the first time a rarely-used type’s static constructor throws deep inside a request instead of at startup.
🚨 The Exception Trap: TypeInitializationException
- If a static constructor throws, .NET wraps it in a `TypeInitializationException` – and marks the type as permanently unusable for the rest of the process; every future access throws the SAME wrapped exception again, even if the underlying problem (a missing file, a bad config value) gets fixed at runtime.
- This means a transient failure the first time `Config` is touched (file locked for a moment) can look like it ‘never recovers’ even after the lock clears, because the CLR cached the failure against the type itself.
⚠️ How to Get Predictable Timing
- If you need initialization to happen at a known point (e.g., right after Main starts, or inside a DI container’s startup phase), do it explicitly in a method you call yourself – don’t rely on the static constructor as a startup hook.
- Touching the type intentionally early (e.g., `RuntimeHelpers.RunClassConstructor`) is possible but rarely worth the complexity – restructuring so initialization isn’t implicit is usually the better fix.
A static constructor doesn’t run when the program starts – it runs when you first ask the type for something, which is a very different promise.



