Monday, 22 September 2025

Singleton vs Static

🟢 1. Singleton

  • What it is: A class where only one object (instance) is ever created.

  • How you use it: You create and use that single object.

Example:

public class AppSettings { private static AppSettings _instance; private AppSettings() { } public static AppSettings Instance { get { if (_instance == null) _instance = new AppSettings(); return _instance; } } } Use: var s = AppSettings.Instance;

Key Points

  • You can implement interfaces (e.g., ILogger).

  • You can use polymorphism (pass it to methods that expect an interface).

  • Created only when needed (lazy load possible).

  • Lives as long as your app runs, but you control initialization.


🟢 2. Static Class

  • What it is: A class that cannot be instantiated at all.
    All members are automatically static.

  • How you use it: You call its methods directly, no object needed.

Example:

public static class MathHelper { public static int Add(int a, int b) => a + b; } // Use: int result = MathHelper.Add(2, 3);

Key Points

  • No object is ever created.

  • Cannot implement interfaces or inherit from other classes.

  • Loaded automatically when your program starts.


🟢 Side-by-Side Comparison

FeatureSingletonStatic Class
Object creationOne object (single instance)No object
Interfaces / InheritYesNo
PolymorphismYesNo
Lazy initializationPossibleNot applicable
State/dataStored inside the single instanceStored in static fields
LifetimeUntil app ends or GC collects (if not static)For whole app domain (always loaded)
Testing (mocking)Easy to mock (pass interface)Hard to mock
Usage exampleLogger.Instance.Log("msg");MathHelper.Add(2,3);

🟢 When to Use

  • Singleton:
    When you need one shared object that may hold state or need an interface (e.g., database connection manager, configuration, logging service).

  • Static Class:
    When you only need utility functions with no state (e.g., math helpers, string helpers).


👉 Quick Rule

  • Need a single shared object?Singleton

  • Need only static helper methods?Static class

No comments:

Post a Comment