65.9K
CodeProject is changing. Read more.
Home

Simple Singleton Pattern in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Nov 7, 2011

CPOL
viewsIcon

16735

Jon Skeet has written an article giving six singleton implementations in C#. The simplest only works in .NET 4:public sealed class Singleton{ private static readonly Lazy lazy = new Lazy(() => new Singleton()); public static Singleton Instance {...

Jon Skeet has written an article giving six singleton implementations in C#. The simplest only works in .NET 4:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton() { }
}

For older .NET versions, the "best" is:

public sealed class Singleton
{
    public static Singleton Instance { get { return Nested.Instance; } }

    private Singleton() { }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested() { }

        internal static readonly Singleton Instance = new Singleton();
    }
}