Singleton VS Static class in C#

Singleton VS Static Class in C# with Examples

In this article, I am going to discuss the Singleton vs Static class in C# with examples. I strongly recommended you to read the Singleton class and Static class articles before proceeding to this article. As part of this article, we are going to discuss the following important pointers.

  1. What are the similarities between Singleton and Static class in C#?
  2. What are the differences between Singleton vs Static class in C#?
  3. Memory Management of Static Class and Singleton Class in C#.
  4. Realtime examples of Static class and Singleton class in C#.
What are the similarities between Singleton and Static class in C#?

Before discussing the differences between them, let’s first discuss the similarities between Singleton vs Static class in C#

  1. Both static class and singleton class can have only one instance of a copy that is available in memory throughout the whole application. They both are used for holding the global state of an application.
  2. Both static classes and singleton classes can be implemented as thread-safe.
What are the differences between Singleton vs Static class in C#?

The most important point that you need to keep in mind is that Static is a language feature whereas Singleton is a design pattern. So both belong to two different areas. With this keep in mind let’s discuss the differences between Singleton vs static class in C#.

  1. We cannot create an instance of a static class in C#. But we can create a single instance of a singleton class and then can reuse that singleton instance.
  2. When the compiler compiles the static class then internally it treats the static class as an abstract and sealed class. This is the reason why neither we create an instance nor extend a static class in C#.
  3. The Singleton class constructor is always marked as private. This is the reason why we cannot create an instance from outside the singleton class. It provides either public static property or a public static method whose job is to create the singleton instance only once and then return that singleton instance each and every time when we called that public static property/method from outside the singleton class.
  4. A Singleton class can be initialized lazily or can be loaded automatically by CLR (Common Language Runtime) when the program or namespace containing the Singleton class is loaded. whereas a static class is generally initialized when it is first loaded for the first time and it may lead to potential classloader issues.
  5. It is not possible to pass the static class as a method parameter whereas we can pass the singleton instance as a method parameter in C#.
  6. In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance with Singleton class. These are not possible with a static class. So the Singleton class is more flexible as compared to static classes.
  7. We can clone the Singleton class object whereas it is not possible to clone a static class. It is possible to dispose of the objects of a singleton class whereas it is not possible to dispose of a static class.
  8. We cannot implement the Dependency Injection design pattern using Static class because the static class is not interface driven.
  9. Singleton means a single object across the application lifecycle, so the scope is at the application level. As we know the static class does not have any Object pointer, so the scope is at the App Domain level.
Memory Management of Static Class vs Singleton Class in C#:

There is a little confusion about the memory management of static vs Singleton class in C#. The most important point that you need to remember is any class whether it is declared itself as static or any member of if it is declared as static then that class or those static members would not be collected by Garbage Collector.

The Static variables or static classes are not stored in the Stack memory. There is some specific space in Heap memory called High-Frequency Heap where the static classes and static variables are stored. This space is beyond the scope of Garbage Collector and hence, the memory gets released only when the corresponding Process or AppDomain gets unload.

As the singleton class holds a static reference, so it cannot be collected by the Garbage Collector (GC) and both (Static and Singleton class) get destroyed only when the corresponding Process or AppDomain gets unloads.

The Static class example in C# – Temperature Converter 

Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius. We are pretty sure that the formulas for converting temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius will not change at all and hence we can use static classes with static methods which do the conversion for us as shown below.

public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string temperatureCelsius)
    {
        // Convert argument to double for calculations.
        double celsius = Double.Parse(temperatureCelsius);

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (celsius * 9 / 5) + 32;

        return fahrenheit;
    }

    public static double FahrenheitToCelsius(string temperatureFahrenheit)
    {
        // Convert argument to double for calculations.
        double fahrenheit = Double.Parse(temperatureFahrenheit);

        // Convert Fahrenheit to Celsius.
        double celsius = (fahrenheit - 32) * 5 / 9;

        return celsius;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Please select the convertor direction");
        Console.WriteLine("1. From Celsius to Fahrenheit.");
        Console.WriteLine("2. From Fahrenheit to Celsius.");
        Console.Write(":");

        string selection = Console.ReadLine();
        double F, C = 0;

        switch (selection)
        {
            case "1":
                Console.Write("Please enter the Celsius temperature: ");
                F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                break;

            case "2":
                Console.Write("Please enter the Fahrenheit temperature: ");
                C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                break;

            default:
                Console.WriteLine("Please select a convertor.");
                break;
        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Run the application and see the output:

Singleton VS Static class in C#

Real-world Examples of Singleton Class:

Some of the real-world scenarios where you can use the singleton design pattern are as follows

  1. Managing Service Proxies
  2. Managing Database Connections
  3. Logging
  4. Caching
  5. Data Sharing
  6. Application Configuration Management

In the next article, I am going to discuss one real-time example of the singleton design pattern using ASP.NET MVC application. Here, in this article, I try to explain Singleton VS Static Class in C# step by step with a simple example. I hope this article will help you with your needs. 

2 thoughts on “Singleton VS Static class in C#”

  1. Now I understood the difference between singleton vs static class in C#. Thank you for this article. Its simple and easy understand.

  2. 3. The Singleton class constructor is always marked as private.

    6. In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance with Singleton class.

    How can you inherit from a singleton class if the constructor is “always marked as private”? Think about that.

Leave a Reply

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