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

T

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

 

Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags