Please enable Javascript for better experience...
Difference between Static Class and Singleton Pattern - C#
By Rahul Kumar Jha | Dec 5, 2019 | In Articles | Total Views [ 6733 ]
Taged In
(1 Like)
Rate

This article discuss about the differences between static class and singleton pattern.

Introduction

Though both looks same and nearby achieve same functionality of maintaining single instance throughout the application but there are certain behavioral differences between two. Singleton is a design pattern that makes sure that your application creates only one instance of the class and internally uses static keyword. 

Static vs Singleton

Static Singleton

We don’t need to instantiate a static class and can access properties and methods with class name.

Instance creation is necessary to access methods and properties. We create instance using static property defined for this purpose.

Static class cannot be passed a parameter in another class

We can pass instances of a singleton as a parameter to another class method.

Static keyword is required in all the methods defined in Static class.

The Singleton class does not require you to use the static keyword everywhere.

Static class does not support interface inheritance. It throw error “static classes cannot implement interfaces”

Singleton class can implement interface

Static variable does not reset until server is restarted.

 

It cannot have instance members. We need to call all the static methods explicitly.

This may have instance members.

Code example

//Static Class
public static class Stat{
static Stat(){
Console.WriteLine("static constr");
}
public static void Get(){
Console.WriteLine("stat method called");
}
}
//Singleton pattern
public class SingleTon{
private static SingleTon obj = null;
private static readonly Object locker = new Object();
private SingleTon(){
}
public int UserId {get;set;}
public static SingleTon GetInstance {
get{
if(obj == null){
lock(locker){
if(obj == null){
obj = new SingleTon();
}
}
}
return obj;
}
}

}

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors