Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Simple Singleton Pattern in C#

, 7 Nov 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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();
    }
}

License

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

Share

About the Author

Henry.Ayoola

United States United States
No Biography provided

Comments and Discussions

 
QuestionSingleton Pattern Example PinmemberDeveloper Hemu Patel8-Aug-14 5:14 
QuestionReally simple PinmemberPeace ON20-Jul-13 1:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411019.1 | Last Updated 7 Nov 2011
Article Copyright 2011 by Henry.Ayoola
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid