Singleton Design Pattern In C#

What is Singleton Design Pattern?

 
Singleton design pattern in C# is one of the most popular design patterns. In this pattern, a class has only one instance in the program that provides a global point of access to it. In other words, a singleton is a class that allows only a single instance of itself to be created and usually gives simple access to that instance.
 
There are various ways to implement a singleton pattern in C#. The following are the common characteristics of a singleton pattern.
  • Private and parameterless single constructor
  • Sealed class.
  • Static variable to hold a reference to the single created instance
  • A public and static way of getting the reference to the created instance.

Advantages of Singleton Design Pattern

 
The advantages of a Singleton Pattern are,
  1. Singleton pattern can implement interfaces.
  2. Can be lazy-loaded and has Static Initialization.
  3. It helps to hide dependencies.
  4. It provides a single point of access to a particular instance, so it is easy to maintain.

Disadvantages of Singleton Design Pattern

 
The disadvantages of a Singleton Pattern are,
  1. Unit testing is a bit difficult as it introduces a global state into an application
  2. Reduces the potential for parallelism within a program by locking.

Singleton class vs. Static methods

 
The following compares Singleton class vs. Static methods,
  1. A Static Class cannot be extended whereas a singleton class can be extended.
  2. A Static Class cannot be initialized whereas a singleton class can be.
  3. A Static class is loaded automatically by the CLR when the program containing the class is loaded.

How to Implement Singleton Pattern in C# code

 
There are several ways to implement a Singleton Pattern in C#.
  1. No Thread Safe Singleton.
  2. Thread-Safety Singleton.
  3. Thread-Safety Singleton using Double-Check Locking.
  4. Thread-safe without a lock.
  5. Using .NET 4's Lazy<T> type.

No Thread Safe Singleton

 
Explanation of the following code,
  1. The following code is not thread-safe.
  2. Two different threads could both have evaluated the test (if instance == null) and found it to be true, then both create instances, which violates the singleton pattern.
    1. public sealed class Singleton1 {  
    2.     private Singleton1() {}  
    3.     private static Singleton1 instance = null;  
    4.     public static Singleton1 Instance {  
    5.         get {  
    6.             if (instance == null) {  
    7.                 instance = new Singleton1();  
    8.             }  
    9.             return instance;  
    10.         }  
    11.     }  
    12. }  

Thread Safety Singleton

 
Explanation of the following code,
  1. The following code is thread-safe.
  2. In the code, the thread is locked on a shared object and checks whether an instance has been created or not. It takes care of the memory barrier issue and ensures that only one thread will create an instance. For example: Since only one thread can be in that part of the code at a time, by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate as false.
  3. The biggest problem with this is performance; performance suffers since a lock is required every time an instance is requested.
    1. public sealed class Singleton2 {  
    2.     Singleton2() {}  
    3.     private static readonly object lock = new object();  
    4.     private static Singleton2 instance = null;  
    5.     public static Singleton2 Instance {  
    6.         get {  
    7.             lock(lock) {  
    8.                 if (instance == null) {  
    9.                     instance = new Singleton2();  
    10.                 }  
    11.                 return instance;  
    12.             }  
    13.         }  
    14.     }  
    15. }  

Thread Safety Singleton using Double-Check Locking

 
Explanation of the following code,
 
In the following code, the thread is locked on a shared object and checks whether an instance has been created or not with double checking.
  1. public sealed class Singleton3 {  
  2.     Singleton3() {}  
  3.     private static readonly object lock = new object();  
  4.     private static Singleton3 instance = null;  
  5.     public static Singleton3 Instance {  
  6.         get {  
  7.             if (instance == null) {  
  8.                 lock(lock) {  
  9.                     if (instance == null) {  
  10.                         instance = new Singleton3();  
  11.                     }  
  12.                 }  
  13.             }  
  14.             return instance;  
  15.         }  
  16.     }  
  17. }  

Thread Safe Singleton without using locks and no lazy instantiation

 
Explanation of the following code:
  1. The preceding implementation looks like a very simple code.
  2. This type of implementation has a static constructor, so it executes only once per Application Domain.
  3. It is not as lazy as the other implementation.
    1. public sealed class Singleton4    
    2. {    
    3.     private static readonly Singleton4 instance = new Singleton4();    
    4.     static Singleton4()    
    5.     {    
    6.     }    
    7.     private Singleton4()    
    8.     {    
    9.     }    
    10.     public static Singleton4 Instance    
    11.     {    
    12.         get    
    13.         {    
    14.             return instance;    
    15.         }    
    16.     }    
    17. }   

Using .NET 4's Lazy<T> type

 
Explanation of the following code:
  1. If you are using .NET 4 or higher then you can use the System.Lazy<T> type to make the laziness really simple.
  2. You can pass a delegate to the constructor that calls the Singleton constructor, which is done most easily with a lambda expression.
  3. Allows you to check whether or not the instance has been created with the IsValueCreated property.
    1. public sealed class Singleton5    
    2. {    
    3.     private Singleton5()    
    4.     {    
    5.     }    
    6.     private static readonly Lazy<Singleton5> lazy = new Lazy<Singleton5>(() => new Singleton5());    
    7.     public static Singleton5 Instance    
    8.     {    
    9.         get    
    10.         {    
    11.             return lazy.Value;    
    12.         }    
    13.     }    
    14. }    
Hope you liked the article. Please let me know the feedback in the comments section.