What is difference between static class & singleton in C#?
Hello guys, I have 2 years of experience in Asp.Net and Asp.Net core. I also know about the static
class and Singleton
design pattern.
I have two classes like below, I want to get value from a config
file:
Singleton:
public class AppSettings
{
private static AppSettings _instance;
private static readonly object ObjLocked = new object();
private IConfiguration _configuration;
protected AppSettings()
{
}
public void SetConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
public static AppSettings Instance
{
get
{
if (null == _instance)
{
lock (ObjLocked)
{
if (null == _instance)
_instance = new AppSettings();
}
}
return _instance;
}
}
public T Get<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
}
And static class:
public static class AppSettings
{
private static IConfiguration _configuration = new Configuration();
public static T Get<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
}
As I know they are the same together. All store in ram and only destroy when application stop.
Anyone can explain to me what is the difference between static class and singleton in C#?
Thanks for any suggestions.
- A1
ANDREW Oct 27 2021
This is some point of my view about them:
- Static still can have a constructor which is internal to that class. This gets invoked when any static method in the class is called.
- Both of them supported lazy-loaded
- Singleton is better to approach from a testing perspective. Unlike static classes, singleton could implement interfaces and you can use mock instances and inject them.
- Static class provides better performance than singleton because static methods are bonded on compile time.
- Singleton is writing unit test easier more than static class because you can pass mock object whenever singleton is expected.
- H0
Huyền Trần thị Oct 26 2021
Static
- A static class allows only static methods.
- Not allow making constructor.
- Can't support inherit or implement from other classes.
- Static objects are stored in the Stack.
- Not allow clone an object to another object.
- We can't implement an interface with a static class
- A static class requires all methods must be static.
Singleton
- Allow creating one or more constructors.
- We can implement an interface with a Singleton class
- Singleton objects are stored in Heap.
- Allow clone an object to another object.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.