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 read the Singleton Design Pattern in C# and Static Class in C# articles before proceeding to this article.

When I take the Interviews, I generally asked a few questions related to static and singleton classes as we used these two classes very frequently in our projects. I generally asked the question “Why do we need to use a Singleton class, if a Static class serves the purpose?” Sometimes I asked the same question in a different manner like “What is the difference Between Singleton and Static Class in C# and when to use one over another in project development?“. So, at the end of this article, you will get a very good understanding of static and singleton classes in C#. 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. Real-Time 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 available in memory throughout the whole application.
  2. They both are used for holding the global state of an application which is going to be common for all clients.
  3. Both Static Classes and Singleton Classes can be implemented as Thread-Safe.
What are the Differences Between Singleton and 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 kept in mind, let’s proceed and discuss the differences between Singleton vs Static class in C#.

  1. We cannot create an instance of a static class in C#, yes one copy of the static class is available in memory, but as a developer, we cannot create an instance of the static class. But, as a developer, we can create a single instance of a singleton class and then we can reuse that singleton instance at many different places of the application.
  2. When the compiler compiles the static class then internally it treats the static class as an Abstract and Sealed Class in C#. This is the reason why neither we create an instance nor we can use the static class as the child class in inheritance. On the other hand, we can create a single instance of the Singleton class as well as we can also use the Singleton class as a child 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 of 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 we called that public static property/method from outside of 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 i.e. Eager Loading. Whereas a static class is generally initialized when it is 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 and inherit from other classes. That means it allows inheritance with the Singleton class. The Singleton class can be created as a Child class also only, you cannot create child classes from the Singleton class. These are not possible with a static class. So, the Singleton class is more flexible as compared to the Static Classes in C#.
  7. We can clone the Singleton Class object (both Deep Copy and Shallow Copy of the Clone Object is possible using the MemberwiseClone method) 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 the 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 the Static and Singleton Class in C#. The most important point that you need to remember is any class whether it is declared as static or any member of 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 unloaded.

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

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# Examples

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 Database Connections
  2. Logging
  3. Caching
  4. Data Sharing
  5. Application Configuration Management

In the next article, I am going to discuss one Real-Time Example of the Singleton Design Pattern in C# using the ASP.NET MVC application. Here, in this article, I try to explain Singleton VS Static Class in C# with Examples. I hope this Singleton VS Static Class in C# with Examples article will help you with your needs. 

5 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.

    1. I think it should be
      6. In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance in (not to use – with/from) Singleton class. I think the author made a typo in that sentence.

      With private constructor we won’t be able to instantiate and due to sealed it won’t allow to inherit it.

      Although, Singleton class can derive from other class or interface(s).

Leave a Reply

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