Singleton VS Static Class in C#

Singleton VS Static Class in C# with Examples

In this article, I will discuss the Singleton vs Static Class in C# with Examples. I strongly recommend you read the Singleton Design Pattern in C# and Static Class in C# articles before proceeding to this article.

When I took 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 why we need to use a Singleton class if a Static class serves the purpose. Sometimes, I asked the same question differently: 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 will 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 application.
  2. They both hold the global state of an application that will 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 in 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 why we neither create an instance nor 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 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 why we cannot create an instance from outside the singleton class. It provides either a 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 call that public static property/method from outside of the singleton class.
  4. A Singleton class can be initialized lazily or 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 impossible 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 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 than 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 impossible 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. The static class has no 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 you need to remember is that if any class, whether it is declared static or any member of it, is declared static, then that class or those static members would not be collected by the 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 variables are stored. This space is beyond the Garbage Collector’s scope; 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 Singleton Class Example in C#
public class Singleton
{
    private static Singleton _instance;

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }

    public void DoSomething()
    {
        // Method implementation
    }
}
The Static Class Example in C# – Temperature Converter 

Here is an example of a static class containing two methods that convert temperature from Celsius to Fahrenheit and Fahrenheit to Celsius. We are sure the formulas for converting temperature from Celsius to Fahrenheit and Fahrenheit to Celsius will not change. 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
Singleton VS Static Class in C#

Singleton and static classes are two different design patterns in C#, each with its own purpose and characteristics. Let’s compare Singleton and static classes in C#:

Singleton Class:
  • Purpose: The Singleton pattern is used to ensure that a class has only one instance throughout the application’s lifetime, and you provide a global point of access to that instance.
  • Instance Creation: The Singleton pattern allows you to control when and how the instance is created. Typically, the instance is created lazily the first time it is requested.
  • Initialization: You can implement complex initialization logic in a Singleton’s constructor or a separate initialization method.
  • Inheritance: Singleton classes can be inherited if not sealed, although this can break the Singleton pattern by allowing multiple instances in subclasses.
  • State Management: Singleton classes can have instance-specific state and behavior.
  • Usage: Singletons are often used for managing resources, configuration settings, logging, database connections, or any situation where you need a single point of control or coordination.
Static Class:
  • Purpose: A static class is used when you want to create utility, helper, or classes that don’t need to maintain state and don’t require instantiation. All members of a static class are also static.
  • Instance Creation: You cannot create instances of a static class. It’s essentially a collection of static members.
  • Initialization: Static classes cannot have instance-specific initialization logic since they cannot be instantiated.
  • Inheritance: Static classes cannot be inherited or extended. They are sealed by nature.
  • State Management: Static classes are typically used for methods, properties, and fields that don’t depend on instance-specific state.
  • Usage: Static classes are suitable for creating libraries, extension methods, utility functions, and other situations where you want to group related functionality without needing instances.
Key Differences:
  • Instantiation: Singleton allows a single instance, while a static class cannot be instantiated.
  • Memory Allocation: Singleton allocates memory for the instance when it’s created; the static class doesn’t allocate memory for instances but for static members.
  • Method Types: Singleton can have instance methods; the static class only has static methods.
  • Inheritance and Interfaces: Singleton can implement interfaces and inherit from other classes, while static classes cannot.
  • Thread Safety: Singleton implementation may require special handling to be thread-safe; static classes don’t have instances, but static members access should be thread-safe if they maintain state.
Use Cases:
  • Singleton: Use when a single instance of a class needs to maintain state and be accessed globally.
  • Static Class: Ideal for utility functions that don’t maintain state and don’t require object instantiation.

The choice between a Singleton and a static class depends on your requirements. Use a Singleton for a single, globally accessible instance with potential state and initialization logic. Use a static class when you want a collection of static members for utility or organizational purposes without needing instances.

In the next article, I will discuss one Real-Time Example of the Singleton Design Pattern in C# using the ASP.NET MVC application. 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. 

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

    1. Whether or not a Singleton class breaks the Open-Closed Principle depends on how it’s designed and used:

      Not Breaking OCP:
      If a Singleton class is designed to allow you to extend its behavior without modifying its source code, then it adheres to the OCP. This can be achieved through techniques such as dependency injection or by providing extension points through interfaces or inheritance. For example, you can have an interface that the Singleton implements, and you can create new classes that implement that interface to extend the behavior of the Singleton without modifying the Singleton class itself.

      Breaking OCP:
      A Singleton class can break the OCP if it tightly couples its behavior with specific concrete classes or doesn’t provide extension points. If you must modify the Singleton class to change its behavior or if it has hard-coded dependencies on specific classes, it may not be open for extension without modification. In such cases, if you need to change the behavior of the Singleton class, you may have to modify its source code, which violates the OCP.

Leave a Reply

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