What is a static constructor, and when does it run?

C# OOP Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

A static constructor (static MyClass() { }) initialises static fields and runs once per type, automatically, before the first instance is created or any static member is accessed. The runtime guarantees it runs exactly once and is thread-safe.

A static constructor sets up a type's static state, and the runtime calls it automatically, exactly once, just before the type is first used — the first time you create an instance or touch a static member. It's guaranteed thread-safe by the CLR, so it's a legitimate way to do one-time lazy initialisation. Two things to know: if it throws, you get a TypeInitializationException and that type is dead for the rest of the process, and its exact timing shifts slightly depending on whether you write it explicitly versus just having static field initialisers.

  • No parameters, no access modifier, can't be called explicitly.
  • Exact timing depends on the beforefieldinit flag: a class with only static field initialisers (no explicit static ctor) may initialise lazily at any point before first use; adding an explicit static ctor makes it precise (right before first use).
  • An exception in a static constructor throws TypeInitializationException and the type is unusable for the rest of the process.
  • Keep it fast and side-effect-free; heavy work here delays first use and is hard to test.