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

Simple Singleton Pattern in C#

Rate me:
Please Sign up or sign in to vote.
3.00/5 (2 votes)
27 Oct 2011CPOL 12.6K   1   2
Another alternative: class Singleton { public static Singleton m_Instance; //Prevent instance creation from other classes private Singleton() { } public static Singleton Instance { get { return m_Instance ?? (m_Instance = new Singleton()); } ...
Another alternative:

C#
class Singleton 
{
    public static Singleton m_Instance;
 
    //Prevent instance creation from other classes
    private Singleton() { }
 
    public static Singleton Instance 
    { 
       get { return m_Instance ?? (m_Instance = new Singleton()); } 
    }
} 

Could you comment pros and cons with alternative-3?

License

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


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

Comments and Discussions

 
GeneralReason for my vote of 1 I'm a big fan of alternative 8, that... Pin
Kabwla.Phone6-Nov-11 21:27
Kabwla.Phone6-Nov-11 21:27 
GeneralWhile Alternative 4 will only load the instance when it is c... Pin
Andrew Rissing27-Oct-11 5:23
Andrew Rissing27-Oct-11 5:23 
While Alternative 4 will only load the instance when it is called, it could have some concurrency issues as two threads could call it instantiating two separate instances. Alternative 3 would not have concurrency issues, but would instantiate the instance the first time the class type is referenced in code.

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

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