CreationalC#verifiedVerified

Singleton Pattern in C#

Ensures a class has only one instance and provides a global point of access to it.

How to Implement the Singleton Pattern in C#

1Step 1: Define the Singleton class with a private constructor

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

    private Singleton() { }

2Step 2: Provide static access to the single instance

    public static Singleton Instance => _instance.Value;

    // Business methods
    public void DoSomething() =>
        Console.WriteLine("Singleton method called");
}

3Step 3: Verify only one instance exists

// Usage:
// var a = Singleton.Instance;
// var b = Singleton.Instance;
// Console.WriteLine(ReferenceEquals(a, b)); // True

Singleton Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Singleton Pattern in the Real World

Think of a country’s president. There can only be one at any time. When anyone needs to communicate with the president, they don’t create a new one—they access the existing one through the official channel (the static method).