Generic Singleton Pattern & C#

Generic Singleton pattern with C# and .NET 4 (or higher)

// T is a class and must have a public default constructor.

public sealed class Singleton<T> where T : class, new()
{
    private static readonly Lazy<T> instance = new Lazy<T>(() => new T());
        
    public static T Instance
    {
        get
        {
            return instance.Value;
        }
    }

    private Singleton() { }
}

Usage:

var myClass = Singleton<MyClass>.Instance;
Etiketler:  C#