Singleton Pattern in C#: What It Is and How It Works
Singleton pattern in C# ensures a class has only one instance and provides a global point of access to it. It is useful when exactly one object is needed to coordinate actions across the system.How It Works
The Singleton pattern works like a single shared resource in a household, such as a single refrigerator that everyone uses. Instead of creating multiple refrigerators, everyone accesses the same one to keep things simple and consistent.
In C#, this means the class controls its own instance creation and keeps a private static variable holding the single instance. When you ask for the instance, the class checks if it already exists; if not, it creates it. This way, no matter how many times you ask, you always get the same object.
This pattern prevents multiple copies of a class from existing, which can save memory and ensure consistent behavior across your program.
Example
This example shows a simple thread-safe Singleton class in C#. It creates only one instance and provides a method to display a message.
using System; public sealed class Singleton { private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton()); // Private constructor prevents external instantiation private Singleton() { } // Public property to access the single instance public static Singleton Instance => instance.Value; public void ShowMessage() { Console.WriteLine("Hello from the Singleton instance!"); } } class Program { static void Main() { Singleton singleton1 = Singleton.Instance; Singleton singleton2 = Singleton.Instance; singleton1.ShowMessage(); // Check if both variables point to the same instance Console.WriteLine(object.ReferenceEquals(singleton1, singleton2)); } }
When to Use
Use the Singleton pattern when you need to control access to a shared resource or service, and only one instance should exist. For example:
- Managing a connection to a database to avoid multiple connections.
- Logging system where all parts of the program write to the same log file.
- Configuration settings that should be consistent and shared across the application.
It helps avoid conflicts and saves resources by preventing duplicate objects.
Key Points
- Singleton ensures only one instance of a class exists.
- Provides a global access point to that instance.
- Commonly implemented with a private constructor and a static property.
- Thread-safe implementations prevent issues in multi-threaded programs.
- Useful for shared resources like configuration, logging, or database connections.