Sobes.tech
Middle

How to implement the Singleton pattern in C#?

sobes.tech AI

Answer from AI

The simplest and most common way is to use a public static property with lazy initialization.

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object lockObject = new object();

    // Private constructor to prevent external instantiation
    private Singleton()
    {
    }

    // Public static property to get the single instance
    public static Singleton Instance
    {
        get
        {
            // Double-checked locking for thread safety
            if (instance == null)
            {
                lock (lockObject)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

    // Additional class methods and properties
    public void SomeMethod()
    {
        // Method logic
    }
}

Another option is using a static constructor and Eager Initialization:

public sealed class Singleton
{
    // Instance is created when the type is initialized
    private static readonly Singleton instance = new Singleton();

    // Private constructor
    private Singleton()
    {
    }

    // Public static property
    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }

    // Additional class methods and properties
    public void SomeMethod()
    {
        // Method logic
    }
}

Using Lazy<T> for lazy and thread-safe initialization:

public sealed class Singleton
{
    // Lazy<T> provides thread-safe lazy initialization
    private static readonly Lazy<Singleton> lazyInstance = new Lazy<Singleton>(() => new Singleton());

    // Private constructor
    private Singleton()
    {
    }

    // Public static property
    public static Singleton Instance
    {
        get
        {
            return lazyInstance.Value;
        }
    }

    // Additional class methods and properties
    public void SomeMethod()
    {
        // Method logic
    }
}