Coder Perfect

Jon Skeet’s clarification on Singleton

Problem

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();
    }
}

In my present C# application, I’d like to use Jon Skeet’s Singleton design.

Concerning the coding, I have two reservations.

Asked by amutha

Solution #1

But, do you really need this pattern? Are you certain you won’t be able to 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() {}
}

Answered by Jon Skeet

Solution #2

Regarding question #1, Jon’s response is right, because by not making the class ‘Nested’ public or internal, he indirectly marks it as private:-). You may do it directly by adding the word ‘private’:

    private class Nested

In response to question (2), the post about beforeinitfield and type initialization simply says that if you don’t have a static constructor, the runtime can do it at any moment (but before you use it). If you have a static constructor, your code in the static constructor may populate the fields, which implies the runtime can only do so when you ask for the type.

Add a static constructor if you don’t want the runtime to ‘proactively’ initialize fields before you use them.

In any case, if you’re using singletons, you either want it to initialize as slowly as feasible, rather than when the runtime thinks it should — or you probably don’t care. I assume you want them as soon as possible based on your question.

That gets us to Jon’s post about singletons, which is, in my opinion, the central theme of this discussion. Oh, and the skepticism:-)

I’d like to point out that his singleton #3, which he labeled as “wrong,” is right (since lock’s implies a memory barrier on exit). When you utilize the instance more than once (which is more or less the goal of a singleton:-)), it should also be faster than singleton #2. So, if you truly need a lazy singleton implementation, I’d probably go with that one – for two reasons: (1) it’s extremely clear what’s going on for everyone who sees your code, and (2) you know what will happen with exceptions.

If you’re curious, I would never use singleton #6 because it can easily result in deadlocks and unusual behavior with exceptions. See lazy’s locking mode, notably ExecutionAndPublication, for more information.

Answered by atlaste

Post is based on https://stackoverflow.com/questions/2550925/singleton-by-jon-skeet-clarification