Singleton implementation with empty static constructor

I reviewed the following Singleton implementation mentioned here here . I understand that static constructors are executed before the first call to the static method or before the object is instantiated, but I did not understand its use here (even from the comments). Can someone help me figure this out?

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}
+5
source share
1 answer

A static constructor does not exist to be called before or after anything else, only as a way to force the compiler not to set a flag beforefieldinit.

More info on this here: What does the beforefieldinit flag do?

. beforefieldinit ( ), , Singleton.Instance, , , .

public void Foo()
{
    if (false)
    {
        var bar = Singleton.Instance.SomeMethod();
    }
}

, beforefieldinit ( - ), singleton, .

, , , , Instance.

+7

All Articles