Implementing the singleton pattern

There are various different ways of implementing the singleton pattern in C#.

The implementation that listed below  is thread-safe, simple, and perform well.

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

 

You can read more about different singleton pattern implementations here


 
 
 

Leave a Reply