简体   繁体   中英

Strange behavior of static constructors

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM