skip to content

In C#, when does a class's static constructor run, how many times, and what happens to the type when it throws?

level: middleimportance: should knowfreq 52%

answer

  1. the runtime decides, not the caller
  2. first instance or first static member
  3. an empty static constructor changes timing
  4. the exception is remembered

basics

~20 s

The runtime runs a static constructor at most once, just before the first instance is created or a static member is referenced. If it throws, the type stays uninitialized and every later use throws TypeInitializationException wrapping the original exception.

solid answer

~40 s

A static constructor (`static PluginRegistry() { ... }`) has no access modifier and no parameters, and nobody calls it: the runtime runs it **once**, under a lock, immediately before the first instance is created or the first static member is referenced. The type's static field initializers run in textual order just before its body. If the type has static field initializers but **no** explicit static constructor, the compiler marks it `beforefieldinit`, and the runtime may run those initializers at any time before the first static field access, which can be later than a static method call. If the static constructor throws, the runtime does not retry it: that access and every later one throw `TypeInitializationException` with the original exception in `InnerException`, and the type stays unusable until the process restarts.

code

csharp · 27 lines
csharp
Console.WriteLine("Main starts");
for (int attempt = 1; attempt <= 2; attempt++)
{
    try
    {
        Console.WriteLine(PluginRegistry.Count);
    }
    catch (TypeInitializationException ex)
    {
        Console.WriteLine($"attempt {attempt}: {ex.Message}");
        Console.WriteLine($"  inner: {ex.InnerException!.GetType().Name}: {ex.InnerException.Message}");
    }
}

static class PluginRegistry
{
    public static readonly int Count;

    static PluginRegistry()
    {
        Console.WriteLine("PluginRegistry static constructor runs");
        string path = "plugins.json";
        if (!File.Exists(path))
            throw new FileNotFoundException("plugin manifest missing", path);
        Count = File.ReadAllLines(path).Length;
    }
}

go deeper

for a junior

Recall that a static constructor runs once, automatically, before the type is first used, and that it takes no access modifier or parameters.

for a middle

Explain the trigger rules, beforefieldinit versus an explicit static constructor, and what TypeInitializationException and its InnerException mean.

for a senior

Diagnose a TypeInitializationException in production from its InnerException, and move fallible I/O out of static constructors so a failure can be retried.

for a principal

Set a rule that static constructors do only local, infallible work, and weigh the timing guarantee against the cost CA1810 describes.

## What a static constructor is A **static constructor** initializes a type rather than an instance. In C# it is declared as `static TypeName() { ... }`, and the compiler enforces its shape: - It takes **no access modifier**: `public static Registry()` fails with `CS0515: access modifiers are not allowed on static constructors`. - It takes **no parameters**: a parameter list gives `CS0132: a static constructor must be parameterless`. - A type has at most one, it is not inherited, and code cannot call it directly. The type's **static field initializers** (`public static readonly int Count = Load();`) are compiled into the same type initializer and run in textual order immediately before the static constructor's body. That is also why a `static readonly` field can be assigned only in its declaration or in the static constructor: both are part of the one type initializer, which runs once. Without any static initializer, static fields keep their default values. ## When it runs With an explicit static constructor, the runtime runs the type initializer **once**, immediately before the first of these: 1. an instance of the type is created; 2. any static member declared in that type is referenced (field, property, method). Referencing a static member declared on a derived class does not run the base class's static constructor. In a run on the .NET 10 SDK, reading `DerivedPlugin.Tag` ran only `DerivedPlugin`'s static initializer and constructor; `BasePlugin`'s static constructor ran later, when the first `new DerivedPlugin()` reached the base constructor. The call is made under a runtime lock, so two threads touching the type at the same time still see one run. The documentation warns against blocking inside a static constructor (waiting on tasks, taking locks, parallel loops), because blocking while the runtime holds the type's initialization lock risks a deadlock. ## beforefieldinit: when there is no static constructor If a class has static field initializers but **no explicit static constructor**, the C# compiler marks the type `beforefieldinit`. The runtime's own definition of that flag is "Initialize the class any time before first static field access." That loosens the timing: | Type has | Initializer timing | Cost | |---|---|---| | Explicit `static` constructor | Precisely before the first instance or static member use | The runtime may need checks at access sites | | Only static field initializers | Any time before the first **static field** access | Cheaper; the JIT can skip most checks | On the .NET 10 SDK, calling a static method that touched no static field did **not** run a `beforefieldinit` type's initializers, while the same call on a type with an empty static constructor did. Code analysis rule CA1810 recommends initializing static fields inline instead of in a static constructor for that performance reason, unless the side effect's timing matters. ## When it throws A static constructor that throws leaves the type **permanently uninitialized** for the life of the process: - the triggering access throws `TypeInitializationException`, whose `InnerException` is the real failure (`FileNotFoundException` in the example); - the runtime **does not run the static constructor again**; later accesses throw `TypeInitializationException` again, with the same inner exception; - nothing in the type can be used until the process restarts. This is why a static constructor that reads a file, a configuration value or a network resource is dangerous: one missing file at the wrong moment disables the type until a restart, and the stack trace points at whatever line first touched the type, not at the cause. ## Safer designs - Keep static constructors to **pure, local, infallible** work: building lookup tables, computing constants. - Move I/O into an explicit `Initialize`/`Load` method or a lazily created instance whose failure can be retried; the lesson on locks and atomics covers `Lazy<T>` and its exception caching. - When a static constructor is needed for timing, document it, because nothing at the call site shows that a type initializer is about to run. - Read `InnerException` first when you see `TypeInitializationException`; the outer message only names the type.

  • Why can adding an empty static constructor change when a C# class's static field initializers run?
    Without one, the compiler marks the type beforefieldinit and the runtime may initialize it any time before the first static field access, possibly later than a static method call. An explicit static constructor removes the flag, so initialization happens exactly before the first instance or static member use, at some cost in access checks.
  • Does reading a derived class's static field run the base class's static constructor?
    No. A static constructor is triggered by use of its own type. On the .NET 10 SDK, reading a derived class's static field ran only the derived type initializer; the base class's ran when the first instance was created and the base constructor was reached.
  • How do you recover from a TypeInitializationException in a running C# process?
    You cannot re-run that type's static constructor, so the type stays broken until restart. Fix the design: move fallible work into an explicit initialization method or a lazily created object that can be retried, and keep static constructors to infallible work.

  • A static constructor runs every time an instance is created.
  • Touching the type again retries a failed static constructor.
  • Static constructors can be public and take parameters.
  • Two threads touching the type at once can run its static constructor twice.
  • Without a static constructor, static initializers always run when the program starts.