Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton implementation with empty static constructor

Tags:

c#

singleton

I was going through the following Singleton implementation mentioned here. I understand static constructors get executed before the first static method call or before te object is instantiated, but did not understand its use here (even from the comments). Could anyone help me understand it?

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;
        }
    }
}
like image 456
Nemo Avatar asked Mar 16 '12 03:03

Nemo


1 Answers

The static constructor is not there in order that it should be called before or after anything else, only as a way to make the compiler not set the beforefieldinit flag.

More information on this here: What does beforefieldinit flag do?

The rationale is to achieve a measure of laziness in the initialization of the singleton object. If beforefieldinit is set (because no static constructor is defined), then executing a method that conditionally references Singleton.Instance is likely to initialize the singleton object, even if the condition is not satisfied and that call is never made.

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

On the other hand, if beforefieldinit is not set (because a static constructor is defined -- even an empty one), then executing that same method will only cause the singleton instance to be initialized if the condition is satisfied and that call is actually made.

That article goes on to point out that this particular implementation is not fully lazy because calling any other static member that you define on the singleton class will also cause Instance to be initialized.

like image 72
Jay Avatar answered Oct 04 '22 04:10

Jay