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. |
Related Articles
- How to get the sizeof a datatype in C#?
- Difference between String and StringBuilder in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- Foreach Loop in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?
- Design Principle vs Design Pattern