CodeBlanks Logo Icon CodeBlanks

Static constructor

C# course · Intermediate · Lesson 11/116

Learn the static constructor that runs once for the class.

Static constructor

A static constructor runs once, before the type is first used. It initializes static fields or performs type-level setup. The declaration is: static Config() { ... }.

It takes no access modifier, no parameters, and cannot be overloaded. Only one is allowed. It is triggered automatically on first use of the type, not with new. It is commonly used to load configuration, prepare caches, or assign constants.

Execution timing guarantee

The timing of a static constructor is guaranteed: when any static field is accessed, a static method is called, or an instance is created — whichever happens first, it triggers then. It runs once and is not triggered again.

This makes it ideal for loading configuration or initial data. But heavy work can slow down the first call to the type, so keep the static constructor short. If it throws, the type becomes unusable.

Exercise Add a static constructor to Config

Add a public static string Version; static field to the Config class. Then declare a static Config() constructor with Version = "1.0"; in the body. Inside Main print Config.Version (no instance; access the static field directly).

Show example solution
public static string Version; and static Config() { Version = "1.0"; }. In Main write Console.WriteLine(Config.Version);
Example solution:
using System;

class Config
{
    public static string Version;

    static Config()
    {
        Version = "1.0";
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(Config.Version);
    }
}

Test yourself

  1. Complete the static constructor declaration

    class Config { ____ Config() { Version = "1.0"; } }
    Show answer
    class Config { static Config() { Version = "1.0"; } }
  2. When does a static constructor run?

    • Once, when the type is first used
    • On every new call
    • Always at program start
    • Never
    Show answer

    Once, when the type is first used — Correct. A static constructor triggers once, on first use of the type.

  3. Match each static constructor feature to its definition

    No access modifier
    Declaration form
    No parameters
    Signature rule
    Runs once
    Execution count
    On first use of type
    Trigger moment

All lessons in Intermediate