Singleton pattern VS Static class in C#

March 7, 2019 C#, Singleton, Static, Design Pattern

I had spent one or two days to try to understand which one of these two approaches I should use for exactly what kind of usage.

Thus, I here wrap up big features among what I have understood.

Common:

  • Static classes and members are stored in a special memory area called “High-Frequency Heap” and this area is excluded from Garbage Collector (GC). Classes that implement the Singleton pattern (let’s say Singleton class) also have static members so these are also excluded from GC. Therefore, these resources are released when a corresponding process or AppDomain end.

  • Both cannot be instantiated so share only one reference throughout an application.

Difference:

  • The static class cannot implement an interface or inherit other class. But it is possible for the Singleton class.

  • Developers can handle the point of time of instantiation by how they implement the laziness). On the other hand, the static class is dependent on Common Language Runtime (CLR).

  • The Singleton class can be written Thread-Unsafe, which means developers should handle this.

In the course of googling, I have seen some said using the Singleton pattern is not good in terms of performance while some said using the static class is not good at performance. So I could not find the answer that says “This is it!”. However, I by myself have concluded like below.

When to use the Singleton pattern:

  • With the common sense, if only one instance is needed over an application. (Logging, caching, DB connection pool and hardware related jobs such as camera and sensor.

When to use the static class:

  • For simple utility-kind classes, global variables, an instance creation class of the Factory pattern, etc…. Mostly, things that can be resolved by using the static class.

References:

Singleton VS Static class in C#
Implementing the Singleton Pattern in C#
Implementing Singleton in C#
C# and beforefieldinit
TYPE INITIALIZATION CHANGES IN .NET 4.0

Happy Coding!