Static Class vs Singleton Class in C#
You learned what is singleton design pattern and how to create a singleton class. Here, you will learn what is the difference between a static class and a singleton class.
A static class can be a singleton class. For example, the following VoteMachine
class is a static class that acts as a singleton class to register the votes of users.
public class VoteMachine
{
private static int _totalVotes = 0;
static VoteMachine()
{
}
public static void RegisterVote()
{
_totalVotes += 1;
Console.WriteLine("Registered Vote #" + _totalVotes);
}
public static int TotalVotes
{
get
{
return _totalVotes;
}
}
}
It will give the correct result in the multi-threaded scenario, as shown below.
public class Program
{
public static void Main()
{
var numbers = Enumerable.Range(0, 10);
Parallel.ForEach(numbers, i =>
{
VoteMachine.RegisterVote();
});
Console.WriteLine(VoteMachine.TotalVotes);
}
}
So, a static class can be a singleton class. It is thread-safe and performs well because we don't need to use locks.
But, what's the difference? Don't we need to create a singleton class at all?
The following lists the difference between a static class and a singleton class:
Static Class | Singleton Class |
---|---|
Cannot inherit the static class in other classes. No Polymorphism. | Can inherit and extend singleton class by having a protected constructor. |
Cannot implement an interface. | Can implement an interface. |
Cannot create and assign an instance to another variable. | Can create one instance and assign it to multiple variables. |
Cannot pass as an argument to a method. | Can be passed as an argument. |
Cannot be serialized. | Can be serialized. |