Click here to Skip to main content
11,582,849 members (71,393 online)
Click here to Skip to main content

Tagged as

Simple Singleton Pattern in C#

, 7 Nov 2011 CPOL 7.8K 3
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

You may also be interested in...

Comments and Discussions

 
QuestionSingleton Pattern Example Pin
Developer Hemu Patel8-Aug-14 4:14
memberDeveloper Hemu Patel8-Aug-14 4:14 
QuestionReally simple Pin
Peace ON20-Jul-13 0:35
memberPeace ON20-Jul-13 0: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
Web04 | 2.8.150603.1 | Last Updated 7 Nov 2011
Article Copyright 2011 by Henry.Ayoola
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid