Static constructor

suggest change

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:


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;

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents