Thread-safe singleton class in C# (use it instead of static..but not always)

Static and Singleton are very different in their usage and implementation. So we need to wisely choose either of these two in our projects.

Singleton is a design pattern that makes sure that your application creates only one instance of the class anytime. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference. 

However, singleton is not the golden rule, there are several cases where a static class is more appropriate.. for example when you want to write extension methods etc…

Below is a simple thread-safe singleton in C#:

public sealed partial class Singleton
{
    private static volatile Singleton instance;
    private static object syncRoot = new Object();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new Singleton();
                }
            }
            return instance;
        }
    }
}

 

Add comment

Categories

Tags