Dot Net For All

Using Singleton Pattern the Right way in C#

In this article I will discuss about the singleton pattern using the C# language. Along with the singleton pattern I will also discuss the correct way to use this pattern in multithreaded applications and ways in which we can make it thread safe. I will also discuss how it is different from the static class using an example.

Singleton Pattern

As from the name we can understand a bit that this a pattern in which we should be able to create single instance of the class across whole of the application. Please check the below code snippet in which I am restricting the creation of only single instance of the class using private constructor.

  public class Singleton
 {
          private static Singleton singletonInstance = CreateSingleton();

          private Singleton()
          {
          }

          private static Singleton CreateSingleton()
          {
             if (singletonInstance == null)
             {
                singletonInstance = new Singleton();
             }

              return singletonInstance;
          }

         public static Singleton Instance
         {
           get { return singletonInstance; } 
         }
 }

As we can see from the above code snippet that I have used a private constructor to restrict the creation of the instance of the class from within the class itself. But what about thread safety, if we are working in a multithreaded application is the above code thread safe? What if two threads enter the if condition of the CreateSingleton() method at same time. We will end up getting two instances of the singleton class which can result to undesired results at run time.

        private static object _lock = new object();
        public static Singleton CreateSingleton()
        {
            if (singletonInstance == null)
            {
                lock (_lock)
                {
                    if (singletonInstance == null)
                    {
                        singletonInstance = new Singleton();
                    }
                }
            }
            return singletonInstance;
        }

In the above code I have used a thread synchronization technique of using lock which will help us to create multiple instances of the same class. Using the lock can be a costlier deal as it takes time to acquire and release lock that is why I have kept a conditional check before acquiring the lock and just to be safe even after acquiring the lock.

A simpler way to create Singleton pattern

In this part of the article I want to discuss a much simpler way to create singleton instance as shown in the below code snippet

    public class Singleton
    {
        private static readonly Singleton singletonInstance = new Singleton();
  
        private Singleton()
        {

        }
   
        public static Singleton Instance { get { return singletonInstance; } }
    }

In this code snippet I have removed the lock object and used readonly static field as the CLR automatically takes care of thread synchronization of static field initializers. You can read more about static fields here in this article.

Difference between Singleton and Static class

  1. Singleton can be inherited from other classes while static cannot be.
  2. Singleton can be passed as parameter to methods.
  3. We can tell exactly when singleton get created and we can dispose it when we no longer need it but that is not true for static class.
  4. Handling mutithreading in static classes can be a trickier but in singleton it can be handled without much fuss.

Singleton Example

In my previous article about the static keyword I have used a static class to hold a collection of object which will be same across whole of the application. But here I want to share an example by using the singleton pattern. Suppose I want to implement the same functionality as of the IList interface for the class in that case I have to implement that interface as shown in the below figure

Though I have implemented only two properties but to achieve all the functionalities of the IList class the implementer has to provide the implementation for all the properties and functions which I leave to the reader.

Now if I wan to use the class I can use it as shown in the below code snippet.

           Singleton sinleton = Singleton.Instance;
           sinleton[0] = new Person() { Name = "Vikram" };

In this article I have shown the usage and implementation of the singleton pattern.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview