Singleton implementation laziness with static constructor

Jon Skeet suggests in his singleton implementation that if you require the maximum laziness for your singleton you should add a static constructor which will make the compiler mark the type as beforefieldinit.

However, I did some testing and it seems that it's more lazy without the beforefieldinit.

Code sample (the private constructor call outputs to console and verifies that the fields were initialized:

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

    public static string Stub()
    {
        return "123";
    }

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    //static Singleton()
    //{
    //}
    private Singleton()
    {
        Console.WriteLine("private ctor");
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

When I call Singleton.Stub() the private constructor is not being hit, and when I uncomment the static constructor, the private constructor is always called.

This is the only difference I could track made by the static constructor.

In my attempts to understand what difference will the beforefieldinit do I've also read Skeet's answer in this post tried it with passing false to DoSomething() - with or without the static constructor the private constructor is not being called.

public static void DoSomething(bool which)
{
    if (which)
    {
        var a = Singleton.Stub();
    }
    else
    {
        Faketon.Stub();
    }
}

When I call Singleton.Stub() the private constructor is not being hit, when I uncomment the static ctor private constuctor is always called.

It's not clear what the value of which is here, but fundamentally you've got four cases:

  • Static constructor, Singleton.Stub called: type initializer is guaranteed to run
  • Static constructor, Singleton.Stub not called: type initializer is guaranteed not to run
  • No static constructor, Singleton.Stub called: type initializer may run, but isn't guaranteed to
  • No static constructor, Singleton.Stub not called: type initializer may run, but isn't guaranteed to
  • The last two cases only differ in that if you change Singleton.Stub to use a static field, the third case becomes "type initializer is guaranteed to run".

    链接地址: http://www.djcxy.com/p/51104.html

    上一篇: 基于Jon Skeet的Singleton的更简单的Singleton

    下一篇: 单例实现懒惰与静态构造函数