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:

Example:

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()
    {
        Console.WriteLine("Yawn!");
    }
}

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

Output:

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.

Animal.Yawn();

This will output:

Animal initialized

Yawn!

See also Exceptions in static constructors and Generic Static Constructors .

Singleton example:

public class SessionManager
{
    public static SessionManager Instance;

Feedback about page:

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


Constructors and Finalizers:
* Static constructor

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
38 Constructors and Finalizers
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script