CodeBlanks Logo Icon CodeBlanks

When static constructors run

C# course · Intermediate · Lesson 34/116

Learn when and how the static constructor runs.

Static constructor

A static constructor runs exactly once, when the class is first loaded. It takes no parameters and has no access modifier. Declaration: static Logger() { ... }.

A static constructor prepares static fields before their first use. It suits reading a configuration file, warming a cache or zeroing a counter. It is triggered on the first access to any static member or on the first instance creation.

When does the static constructor run?

The static constructor is triggered automatically on the first use of the class. First access to a static field, first call to a static method or first instance creation all count.

Example: reading Logger.Count fires the static constructor even before any instance is created, preparing Count. Predicting exactly when it runs is hard; avoid side effects.

Exercise Logging counter

Add a static Logger() constructor to Logger; its body assigns Count = 0;. In Main, call Logger.Log("Started") and print Logger.Count.

Show example solution
Add `static Logger() { Count = 0; }` to Logger. In Main write `Logger.Log("Started"); Console.WriteLine(Logger.Count);`.
Example solution:
using System;

class Logger
{
    public static int Count;

    static Logger()
    {
        Count = 0;
    }

    public static void Log(string message)
    {
        Count++;
        Console.WriteLine(message);
    }
}

class Program
{
    static void Main()
    {
        Logger.Log("Started");
        Console.WriteLine(Logger.Count);
    }
}

Test yourself

  1. Match: static constructor properties

    parameters
    not allowed
    access modifier
    absent
    how often
    once
    trigger
    first static access
  2. Which statement about static constructors is correct?

    • A static constructor can take parameters.
    • A static constructor is marked `public`.
    • A static constructor runs exactly once.
    • A static constructor does not run on instance creation.
    Show answer

    A static constructor runs exactly once. — Correct. A static constructor runs once for the lifetime of the class.

  3. Fill in the blank: static constructor declaration

    class Logger
    {
        public static int Count;
    
        ____
        {
            Count = 0;
        }
    }
    Show answer
    class Logger
    {
        public static int Count;
    
        static Logger()
        {
            Count = 0;
        }
    }

All lessons in Intermediate