Back to: Design Patterns in C# With Real-Time Examples
Singleton VS Static Class in C# with Examples
In this article, I will discuss the Singleton vs. Static Class in C# with Examples. Before proceeding, I strongly recommend you read the Singleton Design Pattern and Static Class in C# articles.
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.
- What are the Similarities Between Singleton and Static class in C#?
- What are the Differences Between Singleton vs Static class in C#?
- Memory Management of Static Class and Singleton Class in C#.
- 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#
- Static Class and Singleton Class can have only one instance available in memory throughout the application.
- They both hold the global state of an application that will be common for all clients.
- 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 you need to remember is that Static is a language feature, whereas Singleton is a Design Pattern. So, both belong to two different areas. With this in mind, let’s proceed and discuss the differences between Singleton vs Static class in C#.
- We cannot create an instance of a static class in C#. Yes, one copy of the static class is available in memory, but we cannot create an instance of the static class as a developer. 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.
- When the compiler compiles the static class internally, it treats it 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#.
- The Singleton Class Constructor is always marked as private. This is why we cannot create an instance 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.
- 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. A static class is generally initialized when it is loaded for the first time, and this may lead to potential classloader issues.
- It is impossible to pass the static class as a method parameter in C #, whereas we can pass the singleton instance as a method parameter in C#.
- In C#, 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#.
Memory Management of Static Class vs Singleton Class in C#:
When the class is loaded, memory for static classes is allocated once in the high-frequency heap (a special heap for static data). This memory allocation is fixed and exists for the lifetime of the application. Since static classes are not instantiated and their resources are allocated directly in the memory, they live throughout the application life cycle and are only cleaned up when the application domain unloads, or the application exits.
Memory for a singleton instance is allocated on the heap when the instance is created, usually the first time it is requested. This memory remains allocated as long as there is a reference to the instance. The memory for the singleton instance is allocated when the instance is created and normally lasts for the duration of the application. However, unlike static classes, it’s possible to implement patterns like using a weak reference for the singleton instance, which allows for the instance to be garbage collected if there are no more references to it.
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Â
The following 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#: When to Use Which?
Use Singleton when:
- You might need to switch from a single instance to multiple instances in the future without changing the API.
- You require lazy initialization or initialization upon first access.
- The class needs to maintain its state for its lifetime.
- You want the class to implement interfaces or manage inheritance hierarchies.
Use Static Class when:
- You are creating utility functions that do not store any state.
- You want a simple and straightforward mechanism to provide global access without any initialization logic.
- You need constants, static configuration settings, or methods that are logically grouped together but do not need to interact with instance data.
The choice between using a Singleton or a static class in C# depends on the specific requirements of your application. A Singleton is more appropriate if you need object-oriented features such as inheritance, interface implementation, and state management. A static class is simpler and more efficient if you need a container for stateless functions or static data that is accessed globally.
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.Â
Now I understood the difference between singleton vs static class in C#. Thank you for this article. Its simple and easy understand.
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.
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).
Point no 6 is right. Here, we are talking about inheritance means we want to make the Singleton Class as a Child Class. The Singleton Class can implement interfaces or abstract classes and can also inherit from another concrete class. Please check the following example where we use this concept.
https://dotnettutorials.net/lesson/singleton-design-pattern-real-time-example-caching-csharp/
Now, I clearly understand the differences between static and Singleton class.
Hey Author,
Could you please tell me why Singleton class is breaking Open-Closed principle.?
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.