| Task vs Thread :👈 | 👉:C# Sharp QA-16 |
Static Class vs Singleton in C# |
Static Class vs Singleton in C#
1. What is a Static Class?
A static class is a class that cannot be instantiated. It contains only static members, which can be accessed directly using the class name without creating an object.
Example:
public static class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
// Usage
int result = Calculator.Add(10, 20);
Key points:
- You cannot create an object of a static class.
- All members must be static.
- A static class cannot implement an instance-based design.
- It cannot implement interfaces.
- It cannot be inherited from or used as a base class.
- It is useful for utility methods and stateless operations.
2. What is a Singleton?
A Singleton is a design pattern that ensures a class has only one instance available for a particular application or dependency-injection container lifetime, depending on its implementation.
Unlike a static class, a singleton is a normal class with an instance that can be shared across multiple consumers.
Example:
public sealed class AppSettings
{
private static readonly AppSettings _instance =
new AppSettings();
private AppSettings()
{
}
public static AppSettings Instance
{
get { return _instance; }
}
public string ApplicationName { get; set; }
}
// Usage
AppSettings settings = AppSettings.Instance;
settings.ApplicationName = "My Application";
Key points:
- The class has one shared instance through its singleton access point.
- The constructor is usually private to prevent external instantiation.
- It can implement interfaces.
- It can inherit from a base class, subject to normal C# inheritance rules.
- It can maintain instance state.
- Thread safety depends on how the singleton is implemented.
3. Key Differences
| Feature | Static Class | Singleton |
|---|---|---|
| Instance creation | Cannot be instantiated | One shared instance is exposed |
| Access | Through the class name | Through an instance or singleton access point |
| Instance state | Cannot have instance fields or properties | Can maintain instance fields and properties |
| Instance methods | Not supported | Supported |
| Interface implementation | Cannot implement interfaces | Can implement interfaces |
| Inheritance | Cannot be inherited from | Can inherit from a base class; often sealed to prevent subclassing |
| Dependency Injection | Cannot be registered as an instance-based service | Can be registered with DI as a singleton service |
| Testing and mocking | Harder to replace or mock directly | Easier to replace through an interface and dependency injection |
| State sharing | Static fields are shared globally within the relevant type context | Instance state is shared through the same singleton instance |
| Typical use | Utility functions and stateless operations | Shared services and stateful components |
4. Singleton Using Dependency Injection in ASP.NET Core
In real-world ASP.NET Core applications, a singleton service is commonly created and managed by the dependency injection container.
public interface IAppInfo
{
string GetApplicationName();
}
public sealed class AppInfo : IAppInfo
{
public string GetApplicationName()
{
return "My Application";
}
}
// Program.cs
builder.Services.AddSingleton<IAppInfo, AppInfo>();
Inject it into a controller or another service:
public class HomeController : Controller
{
private readonly IAppInfo _appInfo;
public HomeController(IAppInfo appInfo)
{
_appInfo = appInfo;
}
public IActionResult Index()
{
return Content(_appInfo.GetApplicationName());
}
}
The DI container creates and reuses the same AppInfo instance for that service registration within the application's service provider.
Important: Singleton services are shared across requests, so avoid storing request-specific or user-specific mutable data in their instance fields. Also, do not inject scoped services directly into singleton services without an appropriate scope-management strategy.
5. When Should You Use Each?
Use a static class when:
- You need simple, stateless utility methods.
- You do not need dependency injection.
- You do not need polymorphism or interface-based substitution.
Examples: mathematical calculations, string formatting helpers, and simple conversion utilities.
Use a singleton service when:
- You need one shared service instance.
- You want to use dependency injection.
- You need to implement an interface or support test substitutes.
- You need to share carefully managed state or reusable resources.
Examples: application-wide configuration services, in-memory caches, and reusable services that manage shared resources.
6. Important Interview Points
- A static class is a C# language feature; Singleton is a design pattern.
- A singleton is an object, whereas a static class is not an object you can instantiate.
- Both can expose functionality globally, but their design and testing characteristics differ.
- A singleton does not automatically guarantee thread-safe access to mutable state.
- In ASP.NET Core, prefer dependency injection with
AddSingleton()when you need a shared application service. - Do not use a singleton merely to make every class globally accessible; this can create tight coupling and shared-state problems.
7. Quick Summary
Static Class: Use it for stateless helper functionality that does not require an object instance.
Singleton: Use it when you need one shared object, particularly when dependency injection, interfaces, or instance state are important.
Best practice: In modern ASP.NET Core applications, prefer dependency injection for application services and use static classes primarily for appropriate utility operations.
| Task vs Thread :👈 | 👉:C# Sharp QA-16 |