Is this a valid, lazy, thread safe Singleton implementation for C #?

I implemented the Singleton pattern as follows:

public sealed class MyClass {

    ...

    public static MyClass Instance {
        get { return SingletonHolder.instance; }
    }

    ...

    static class SingletonHolder {
        public static MyClass instance = new MyClass ();
    }
}

From Googling to implement C # Singleton, it doesn't look like it's the usual way to do something in C #. I found one such implementation, but the SingletonHolder class was not static and included an explicit (empty) static constructor.

Is this a valid, lazy, thread safe way to implement the Singleton pattern? Or am I missing something?

+5
source share
1 answer

John Skeet wrote an article on the implementation of the Singleton pattern in C #.

lazy implementation - version 5:

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

, , , .

+6

All Articles