Singleton Design Pattern in C#

Singleton Design Pattern in C# with an Example

In this article, I am going to discuss the Singleton Design Pattern in C# with an example. Please read our previous article where we discussed the basics of the Creational Design Pattern. The Singleton Design Pattern falls under the creational pattern category. As it belongs to the creational pattern category, it is going to be dealing with object creation and manipulation. As part of this article, we are going to discuss the following pointers.

  1. What is Singleton Design Pattern?
  2. What are the Advantages of using the Singleton Design Pattern?
  3. Implementation Guidelines of Singleton Design Pattern in C#.
  4. Example of the Singleton Design Pattern using C#.
  5. Some Real-time scenarios where you can use the Singleton Design Pattern.
  6. What are the Disadvantages of using the Singleton Design Pattern in C#?
What is Singleton Design Pattern in C#?

We need to use the Singleton Design Pattern in C# when we need to ensures that only one instance of a particular class is going to be created and then provide simple global access to that instance for the entire application.

Singleton Design Pattern in C#

As you can see in the above diagram, different clients (NewObject a, NewObject b and NewObject n) trying to get the singleton instance.  Once the client gets the singleton instance then they invoke the methods. If this is confused at the moment then don’t worry we will discuss it with practice. 

What are the Advantages of using the Singleton Design Pattern in C#?

The Advantages of using the Singleton Design Pattern in C# are as follows.

  1. The first and most important advantage of using the singleton design pattern in C# is that it takes care of concurrent access to the shared resource. That means if we are sharing a resource with multiple clients simultaneously, then concurrent access to that resource is well managed by the singleton design pattern.
  2. It can be lazy-loaded and also has Static Initialization.
  3. To share common data i.e. master data and configuration data which is not changed that frequently in an application. In that case, we need to cache the objects in memory.
  4. As it provides a single global point of access to a particular instance, so it is easy to maintain.
  5. To reduce the overhead of instantiating a heavy object again and again.
Implementation Guidelines of Singleton Design Pattern in C#:

The following are the implementation guidelines for using the singleton design pattern in C#.

  1. You need to declare a constructor that should be private and parameterless. This is required because it is not allowed the class to be instantiated from outside the class. It only instantiates from within the class.
  2. The class should be declared as sealed which will ensure that it cannot be inherited. This is going to be useful when you are dealing with the nested class. We will discuss this scenario with an example in our upcoming article.
  3. You need to create a private static variable that is going to hold a reference to the single created instance of the class if any.
  4. You also need to create a public static property/method which will return the single created instance of the singleton class. This method or property first check if an instance of the singleton class is available or not. If the singleton instance is available, then it returns that singleton instance otherwise it will create an instance and then return that instance.
Example of the Singleton Design Pattern using C#

Let us understand the Singleton Design pattern in C# with an example. There are many ways, we can implement the Singleton Design Pattern in C# are as follows.

  1. No Thread-Safe Singleton design pattern.
  2. Thread-Safety Singleton implementation.
  3. The Thread-Safety Singleton Design pattern implementation using Double-Check Locking.
  4. Thread-Safe Singleton Design pattern implementation without using the locks and no lazy instantiation.
  5. Fully lazy instantiation of the singleton class.
  6. Using .NET 4’s Lazy<T> type.

In this article, we are going to discuss the No Thread-Safe Singleton Design Pattern implementation in C#. The rest of the implementations are going to be discussed one by one from our next article. So, create a console application with the name SingletonDemoV1. as shown below.

Singleton Design Pattern in C#

Once you click on the OK button it will take some time to create the project. Once the project is created let’s add a class file with the name Singleton.cs and then copy and paste the following code in it.

Singleton.cs
namespace SingletonDemo
{
    public sealed class Singleton
    {
        private static int counter = 0;
        private static Singleton instance = null;
        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }
        
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }

        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }
}
Explanation of the above code.

We created the Singleton class as sealed which ensures that the class cannot be inherited and object instantiation is restricted in the derived class. The class is created with a private constructor which will ensure that the class is not going to be instantiated from outside the class. Again we declared the instance variable as private and also initialized it with the null value which ensures that only one instance of the class is created based on the null condition. The public property GetInstance is used to return only one instance of the class by checking the value of the private variable instance. The public method PrintDetails can be invoked from outside the class through the singleton instance.

We are done with our first version of the singleton design pattern implementation. Let’s use this in our Main method of Program class. So, copy and paste the following code in the program class

Program.cs
namespace SingletonDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton fromTeachaer = Singleton.GetInstance;
            fromTeachaer.PrintDetails("From Teacher");
            Singleton fromStudent = Singleton.GetInstance;
            fromStudent.PrintDetails("From Student");

            Console.ReadLine();
        }
    }
}

Run the application and it will give you the following output.

Singleton Design Pattern in C#

From the above output, it clearly shows that the private constructor is executed only once even though we have called the GetInstance property twice and print the counter value to 1 hence it proves that the singleton instance is created only once. The way we implement the singleton design pattern in the above example is not to thread-safe. It means in a multithreaded environment, it will able to create multiple instances of the singleton class. How to make the singleton class thread-safe we will discuss in the Thread-Safe Singleton Design Pattern article.

Some Real-time scenarios where you can use the Singleton Design Pattern:

Service Proxies: As we know invoking a Service API is an extensive operation in an application. The process that taking most of the time is creating the Service client in order to invoke the service API. If you create the Service proxy as Singleton then it will improve the performance of your application.

Facades: You can also create the Database connections as Singleton which can improve the performance of the application.

Logs: In an application, performing the I/O operation on a file is an expensive operation. If you create your Logger as Singleton then it will improve the performance of the I/O operation.

Data sharing: If you have any constant values or configuration values then you can keep these values in Singleton So that these can be read by other components of the application.

Caching: As we know fetching the data from a database is a time-consuming process. In your application, you can cache the master and configuration in memory which will avoid the DB calls. In such situations, the Singleton class can be used to handle the caching with thread synchronization in an efficient manner which drastically improves the performance of the application. 

What are the Disadvantages of using the Singleton Design Pattern in C#?

The disadvantages of using the Singleton Design Pattern in C# are as follows:

  1. Unit testing is very difficult because it introduces a global state into an application.
  2. It reduces the potential for parallelism within a program because to access the singleton instance in a multi-threaded environment, you need to serialize the object by using locking.

In the next article, I am going to discuss why we need to use the sealed keyword to the Singleton class as we already have a private constructor. Here, in this article, I try to explain the basics of the Singleton Design Pattern in C# step by step with a simple example. I hope you understood why we need the singleton design pattern.

2 thoughts on “Singleton Design Pattern in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *