Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

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.

Example: Singleton Class
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.

Example:
public class Program
{
	public static void Main()
	{
		var numbers = Enumerable.Range(0, 10);
		Parallel.ForEach(numbers, i =>
		{			
			VoteMachine.RegisterVote();
		});
		Console.WriteLine(VoteMachine.TotalVotes);
	}
}
Try it

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 ClassSingleton 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.
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.