2

I have the following types:

internal struct TestStruct
{
    static TestStruct()
    {
        Console.WriteLine("Constructor has been called!");
    }

    public void SomeMethod()
    {
    }
}


internal struct OtherTestStruct
{
    static OtherTestStruct()
    {
        Console.WriteLine("This never gets displayed. But why???");
    }
}

Why static constructor is called only when some method was called?

1
  • 4
    Its optimization. The static constructor doesn't need to be called if the class is never referenced. Commented Jun 24, 2016 at 21:59

1 Answer 1

8

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.

Source

The static constructor is only called when needed. In your second example it's not needed because no instance is created nor are any static members referenced.

The page goes on to list some other properties of static constructors. The most notable are:

  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.

So, while the summary on that MSDN page quoted states that it is called before any static members are referenced, you can't guarantee exactly when that might be. Therefore, you should probably be careful about what code you do execute in the constructor.

Sign up to request clarification or add additional context in comments.

8 Comments

The static constructor a class is not guaranteed to be executed before a static method of the same class?
@Khan - that's not 100% clear. The summary I quoted would indicate that it is, but the bullet point casts doubt on that.
@Khan A method is one particular type of member, so the quote is saying a static constructor will be executed before a static method of the same class.
@ChrisF You seem to be reading the second bullet point you quoted as "the runtime is free to not call the static constructor even if the earlier quotes guarantee that it will be called", which is not a reasonable interpretation and not what it says. :) It just means that there is no language support for forcing a static constructor call.
@hvd - fair enough.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.