Showing posts with label Singleton Pattern Real-Time Example in C#. Show all posts
Showing posts with label Singleton Pattern Real-Time Example in C#. Show all posts

Tuesday, September 23, 2025

Understanding Singleton Design Pattern in C# with Real-Time Examples

 📌 Introduction

In software design patterns, the Singleton Design Pattern plays a crucial role when we want to ensure that only one instance of a class exists throughout the lifecycle of an application. Singleton provides a global access point to this single instance, making it widely used in scenarios like logging, configuration management, caching, and database connections.

In this article, we will explore:

  • What is Singleton Design Pattern?

  • Importance of private constructor, static variable, and static constructor.

  • Real-time example with C#.

  • Difference between Singleton and Static class.

  • Lazy Singleton with thread safety implementation.



🚀 What is Singleton Design Pattern?

The Singleton Pattern ensures that a class has only one instance and provides a global access point to it. This prevents duplicate objects from being created unnecessarily and helps in maintaining a single state across the application.

For example, imagine a Logger class – instead of creating multiple loggers in different modules, a singleton logger ensures all logs go through one centralized object.


🔎 Importance of Components in Singleton

✅ Private Constructor

  • Prevents the creation of an object using the new keyword.

  • Ensures external classes cannot instantiate multiple objects.

private Logger() { }

✅ Static Variable

  • Stores the single instance of the class.

  • Ensures only one instance exists globally.

private static Logger _instance;

✅ Static Constructor

  • Initializes the singleton instance only once, automatically by the CLR.

  • Ensures thread-safe initialization.

static Logger() { _instance = new Logger(); }

💡 Real-Time Example: Logger Singleton

public sealed class Logger { private static readonly Logger _instance; // Static constructor static Logger() { _instance = new Logger(); } // Private constructor private Logger() { } // Public global access point public static Logger Instance => _instance; public void Log(string message) { Console.WriteLine($"[Log]: {message}"); } } // Usage class Program { static void Main() { Logger.Instance.Log("Application started"); Logger.Instance.Log("User logged in"); } }

📌 Output:

[Log]: Application started [Log]: User logged in

Here, Logger.Instance always points to the same object.


🆚 Singleton vs Static Class

FeatureSingleton ClassStatic Class
InstanceSingle object (controlled creation)No instance (direct static access)
InheritanceCan implement interfaces & inheritCannot inherit or implement interfaces
FlexibilityCan be extended, mocked, injected (DI)Rigid, cannot be mocked/tested
State ManagementCan maintain state inside instanceUses static fields (global state)
InitializationCan use lazy loading for performanceAlways loaded at first access

👉 Use Singleton for shared resources like Database Connections, Logger, Cache Manager.
👉 Use Static Class for utility/helper methods like Math or Convert.


🛡️ Lazy Singleton with Thread Safety in C#

In high-performance applications, it is better to create the singleton instance only when needed (Lazy Initialization). This saves memory and improves performance.

✅ Thread-Safe Lazy Singleton Example

public sealed class ConfigurationManager { // Lazy ensures thread safety and lazy initialization private static readonly Lazy<ConfigurationManager> _instance = new Lazy<ConfigurationManager>(() => new ConfigurationManager()); // Private constructor private ConfigurationManager() { Console.WriteLine("Configuration Manager Initialized"); } // Global access point public static ConfigurationManager Instance => _instance.Value; public string GetConfig(string key) { return $"Value of {key}"; } } // Usage class Program { static void Main() { var config1 = ConfigurationManager.Instance; Console.WriteLine(config1.GetConfig("ConnectionString")); var config2 = ConfigurationManager.Instance; Console.WriteLine(ReferenceEquals(config1, config2)); // true } }

📌 Output

Configuration Manager Initialized Value of ConnectionString True

✔ The constructor runs only once.
✔ Both config1 and config2 point to the same instance.
✔ The Lazy<T> type ensures thread safety automatically.


🎯 Conclusion

The Singleton Design Pattern in C# is one of the most powerful and commonly used design patterns for managing shared resources. With the help of private constructor, static variables, and static constructors, we can ensure that only one instance exists throughout the application.

For modern .NET applications, the Lazy Singleton with thread safety approach is the most efficient and recommended implementation.

Key Takeaway:

  • Use Singleton when you need a shared, single instance with controlled access.

  • Use Static Class when you need utility functions without state.

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages