Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor is called before any static members are referenced

According to the docs:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

But i saw in stackoverflow post, the following quote from the C# specification:

If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor.

It's contradicting, i don't understand what come first, the static constructor or the static member initialization.

like image 904
T.S Avatar asked Feb 04 '23 21:02

T.S


1 Answers

Consider this class:

public static class TestStatic
{
    public static int SomeValue = GetValue();

    static TestStatic()
    {
        Console.WriteLine("Constructor");
    }

}

And this supporting method:

public static int GetValue()
{
    Console.WriteLine("GetValue");
    return 5;
}

If you run this code:

Console.WriteLine(TestStatic.SomeValue);

The output you will get is:

GetValue
Constructor
5

So you can see that both of the statements you posted are correct. The constructor is called before the static member (SomeValue) is referenced and the static field initialiser is called before the constructor.

like image 91
DavidG Avatar answered Feb 07 '23 10:02

DavidG