Click here to Skip to main content
15,886,003 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Simple Singleton Pattern in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
7 Nov 2011CPOL 16.5K   2  
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:


C#
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:


C#
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();
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --