Implement a singleton pattern in C#

Implementing the Singleton pattern in C#

With the help of this blog post, we are gonna learn to implement singleton in C# and make it thread safe.

First of all, What is Singleton Pattern?

A singleton is a class that only allows a single instance of itself to be created, and usually gives simple access to that instance. Ensures a class has only one instance and provides a global point of access to it.

Ok, now we know what is Singleton, but why do we want to use it? We can use static classes, then why introduce new design pattern and make things complicated right?

Advantages of Singleton:

  • It provides a single point of access to a particular instance, so it is easy to maintain.
  • It helps to hide dependencies.
  • It can be lazy loaded.
  • It can be implemented interfaces.
  • It can be extended into a factory pattern.

Now, we want to see how to implement Singleton in C# and make it thread-safe. There are many ways to implement a singleton, today we are gonna see a couple of ways using which you can create a singleton in a thread-safe way. Here is how you can implement them:

public sealed class Singleton
{
    Singleton()
    {
    }
 
    private static readonly object padlock = new object();
 
    private static Singleton instance = null;
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

In the above-mentioned approach, the thread is locked on the shared object and checks whether an instance has been created or not. This takes care of memory issue. But one of the biggest issue with this is performance, it suffers since a lock is required every time an instance is created.

public sealed class Singleton
{
    private Singleton()
    {
    }
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance
    {
        get
        {
            return lazy.Value;
        }
    }
}

This approach has all the advantages mentioned above and performance does not get impacted and implementing it is quite simple too. All you need to do is pass a delegate to the constructor that calls the Singleton constructor, which is done most easily with a lambda expression. It also allows you to check whether or not the instance has been created with the IsValueCreated property.

Thanks for dropping by !!! Feel free to comment to this post or you can drop me an email at naik899@gmail.com

Leave a Reply