Static constructor

Download c# eBook


A static constructor is called the first time any member of a type is initialized, a static class member is called or a static method. The static constructor is thread safe. A static constructor is commonly used to:

  • Initialize static state, that is state which is shared across different instances of the same class.
  • Create a singleton


class Animal
    // * A static constructor is executed only once,
    //   when a class is first accessed.
    // * A static constructor cannot have any access modifiers
    // * A static constructor cannot have any parameters
    static Animal()
        Console.WriteLine("Animal initialized");

    // Instance constructor, this is executed every time the class is created
    public Animal()
        Console.WriteLine("Animal created");

    public static void Yawn()

var turtle = new Animal();
var giraffe = new Animal();


Animal initialized
Animal created
Animal created

View Demo

If the first call is to a static method, the static constructor is invoked without the instance constructor. This is OK, because the static method can't access instance state anyways.


This will output:

Animal initialized

See also Exceptions in static constructors and Generic Static Constructors .

Singleton example:

public class SessionManager
    public static SessionManager Instance;

    static SessionManager()
        Instance = new SessionManager();


Contributors: 10
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook