DEV Community

Cover image for C# - Singleton Design Pattern with Lazy Initialization
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Singleton Design Pattern with Lazy Initialization

The Singleton design pattern ensures that a class has only one instance and provides a global access point to that instance. In C#, you can implement a Singleton pattern using lazy initialization for efficient resource usage. Here's an example of how to do it:

using System;

public class Singleton
{
    private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());

    // Private constructor to prevent instantiation from other classes.
    private Singleton()
    {
        Console.WriteLine("Singleton instance created.");
    }

    // Public static method to access the Singleton instance.
    public static Singleton Instance => instance.Value;

    public void SomeMethod()
    {
        Console.WriteLine("Singleton method called.");
    }
}

class Program
{
    static void Main()
    {
        // Access the Singleton instance
        Singleton singleton1 = Singleton.Instance;
        Singleton singleton2 = Singleton.Instance;

        // Verify that both instances are the same
        Console.WriteLine($"singleton1 == singleton2: {singleton1 == singleton2}");

        // Use the Singleton
        singleton1.SomeMethod();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We define a Singleton class with a private constructor, preventing direct instantiation from other classes.

  2. We use Lazy<T> to ensure lazy initialization of the Singleton instance. This means that the instance is created only when it is first accessed, improving performance and resource usage.

  3. The Instance property provides a static way to access the Singleton instance.

  4. In the Main method, we demonstrate that two calls to Singleton.Instance result in the same instance being returned, confirming that it's indeed a Singleton.

Implementing the Singleton pattern with lazy initialization ensures thread safety, minimizes resource usage, and provides a single point of access to a shared instance, making it a valuable design pattern in many scenarios, such as managing application configuration, logging, and caching.

Top comments (0)