Singleton Design Pattern With C# Sample

What is Singleton Design Pattern?

 
Singleton design pattern is a creational design pattern. It is used to maintain single instance throughout the application.
 

When to use Single Design pattern?

 
When our requirement requires a single instance through the application and if it has to inherit by some other interface/class or if memory management should be dynamic we can take steps to implement this design pattern.
 
If our aim is to create only single instance I recommend to use static class.
 

Where we can use it?

 
For Database connection, logging, caching purpose etc.

 
Rules to implement Singleton

  1. It should have Global access
  2. It should be not be inherited by some other class; i.e., we have to seal the class with sealed key word / we can make constructor private to stop inheritance.
  3. Constructor should be Private, to prevent the creation of instance from outside the class. And once we define constructor as private it will also help to stop being inherited.
Below is the code which defined the Singleton design pattern. Below code is not thread safe. 
  1. namespace Singleton.Design.Pattern  
  2. {  
  3.     public class SingletonSample  
  4.     {  
  5.         private static SingletonSample _instance;  
  6.   
  7.         /// <summary>  
  8.         /// Instance will set only once initially when _insatnce is null  
  9.         /// </summary>  
  10.         public static SingletonSample Instance => _instance = _instance ?? new SingletonSample();  
  11.   
  12.         /// <summary>  
  13.         /// To prevent inheritance of this class and to prevent the creation of instance from outside the class  
  14.         /// </summary>  
  15.         private SingletonSample()  
  16.         {  
  17.             
  18.         }  
  19.     }  
  20. }  
Below is the code of accessing singleton instance. To make sure we have single instance, I am accessing the class with Instance 10 times and matching with some refInstance object, along with printing object reference hash code
  1. using System.Collections.Generic;  
  2. using static System.Console;  
  3.   
  4. namespace Singleton.Design.Pattern  
  5. {  
  6.     class Program  
  7.     {  
  8.         public static void Main()  
  9.         {  
  10.             List<SingletonSample> instances = new List<SingletonSample>();  
  11.             for (int i = 0; i < 10; i++)  
  12.             {  
  13.                 instances.Add(SingletonSample.Instance);  
  14.             }  
  15.   
  16.             var refInstance = SingletonSample.Instance;  
  17.             WriteLine($"Object refInstance Hash code:{refInstance.GetHashCode()}");  
  18.             foreach (var instance in instances)  
  19.             {  
  20.                 if (instance.Equals(refInstance))  
  21.                     WriteLine($"Found same object with Hash code:{instance.GetHashCode()}");  
  22.                 else  
  23.                     WriteLine($"Found mismatch object with Hash code:{instance.GetHashCode()}");  
  24.             }  
  25.               
  26.             ReadLine();  
  27.   
  28.         }  
  29.     }  
  30. }  
Below is the output window after execution of above code.
 
Singleton Design Pattern With C# Sample
 
If we are using the threads in our application and we are expecting to maintain singleton instance even though the class is accessed by threads, in these kind of cases we need thread safe singleton class.
 
Below is the thread safe code.
  1. using System;  
  2.   
  3. namespace Singleton.Design.Pattern  
  4. {  
  5.     public class ThreadSafeSingleton  
  6.     {  
  7.         private static ThreadSafeSingleton _instance;  
  8.         private static object threadSafe = new object();  
  9.         public static string Praposal;  
  10.   
  11.         public static ThreadSafeSingleton GetInstance(string proposal)  
  12.         {  
  13.             //lock keyword which will be used to synchronize threads  
  14.             lock (threadSafe)  
  15.             {  
  16.   
  17.                 if (_instance is null)  
  18.                 {  
  19.                     Praposal = proposal;  
  20.                     _instance = new ThreadSafeSingleton();  
  21.                 }  
  22.             }  
  23.             return _instance;  
  24.         }  
  25.   
  26.         private ThreadSafeSingleton()  
  27.         {  
  28.             
  29.         }  
  30.   
  31.         public void PrintProposalReply()  
  32.         {  
  33.             Console.WriteLine(Praposal);  
  34.         }  
  35.     }  
  36. }  
In thread safe code we can see that we are using lock keyword which will be used to synchronize threads. If multiple threads try to access the instance of class, the first will acquire lock and will proceed to the next, while the rest will wait until the first thread finishes it’s execution in that class. And again when the second thread, third thread and so on moves one by one synchronously and as the first thread is an already created instance,the rest of the threads will use the same instance for further execution.
 
Below is the code where we are creating multiple instance in 4 different threads and while creating each instance we are passing thread name. As per the above explanation, class should maintain the proposal of first thread which is hit to thread safe singleton class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Threading;  
  4. using static System.Console;  
  5.   
  6. namespace Singleton.Design.Pattern  
  7. {  
  8.     class Program  
  9.     {  
  10.         public static void Main()  
  11.         {  
  12.             Thread threadA = new Thread(() => PrintThreadName(nameof(threadA)));  
  13.             Thread threadB = new Thread(() => PrintThreadName(nameof(threadB)));  
  14.             Thread threadC = new Thread(() => PrintThreadName(nameof(threadC)));  
  15.             Thread threadD = new Thread(() => PrintThreadName(nameof(threadD)));  
  16.   
  17.             threadA.Start();  
  18.             threadB.Start();  
  19.             threadC.Start();  
  20.             threadD.Start();  
  21.             threadA.Join();  
  22.             threadB.Join();  
  23.             threadC.Join();  
  24.             threadD.Join();  
  25.   
  26.             ReadLine();  
  27.   
  28.         }  
  29.   
  30.         private static void PrintThreadName(string proposal)  
  31.         {  
  32.             var s = ThreadSafeSingleton.GetInstance(proposal + " Proposed to create instance");  
  33.             s.PrintProposalReply();  
  34.         }  
  35.     }  
  36. }  
Below is the output of Thread Safe Singleton accessing code. In the below output we can see that thread A hit the Thread Safe Singleton code and created instance and the other 3 threads i.e. thread, threadC, threadD,  access the same instance created by threadA
 
Singleton Design Pattern With C# Sample
 

Summary

 
In this article we learned how to create singleton instance and where to use it. And also we saw how to implement thread safe singleton instance.