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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With