Singleton by Jon Skeet clarification

amutha picture amutha · Mar 31, 2010 · Viewed 45.9k times · Source
public sealed class Singleton
{
    Singleton() {}

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

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested() {}
        internal static readonly Singleton instance = new Singleton();
    }
}

I wish to implement Jon Skeet's Singleton pattern in my current application in C#.

I have two doubts on the code

  1. How is it possible to access the outer class inside nested class? I mean

    internal static readonly Singleton instance = new Singleton();
    

    Is something called closure?

  2. I am unable to understand this comment

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    

    what does this comment suggest us?

Answer

Jon Skeet picture Jon Skeet · Mar 31, 2010
  1. No, this is nothing to do with closures. A nested class has access to its outer class's private members, including the private constructor here.

  2. Read my article on beforefieldinit. You may or may not want the no-op static constructor - it depends on what laziness guarantees you need. You should be aware that .NET 4 changes the actual type initialization semantics somewhat (still within the spec, but lazier than before).

Do you really need this pattern though? Are you sure you can't get away with:

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    public static Singleton Instance { get { return instance; } }

    static Singleton() {}
    private Singleton() {}
}