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

Simple Singleton Pattern in C#

Rate me:
Please Sign up or sign in to vote.
3.83/5 (20 votes)
8 Jul 2011CPOL 33.4K   12   14
This should do it as well:class Singleton { public static readonly Singleton m_Instance = new Singleton(); // Prevent instance creation from other classes private Singleton() { } public static Singleton Instance { get { return m_Instance; } }}And it is "Singleton",...

This should do it as well:


C#
class Singleton {
    public static readonly Singleton m_Instance = new Singleton();

    // Prevent instance creation from other classes
    private Singleton() { }

    public static Singleton Instance { get { return m_Instance; } }
}

And it is "Singleton", not a "single Ton"... SCNR

License

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



Comments and Discussions

 
QuestionVote 2 Pin
Sinisa Hajnal23-Mar-16 1:21
professionalSinisa Hajnal23-Mar-16 1:21 
GeneralMy vote of 2 Pin
Bartlomiej Filipek6-Oct-13 23:31
Bartlomiej Filipek6-Oct-13 23:31 
GeneralMy vote of 2 Pin
Akhil Mittal26-Feb-13 22:54
professionalAkhil Mittal26-Feb-13 22:54 
GeneralMy vote of 2 Pin
Oleksandr Kulchytskyi29-Dec-12 3:19
professionalOleksandr Kulchytskyi29-Dec-12 3:19 
GeneralReason for my vote of 2 This alternative is not 'lazyloading... Pin
Kabwla.Phone1-Nov-11 3:02
Kabwla.Phone1-Nov-11 3:02 
GeneralRe: Reason for my vote of 2This alternative is not 'lazyloading... Pin
Ian A Davidson10-Apr-13 15:19
Ian A Davidson10-Apr-13 15:19 
As far as "Lazy loading" goes, in terms of when the Singleton instance is created there is unlikely to be any noticeable difference between:

Option 1:
C#
sealed class Singleton
{
    private static Singleton m_Instance = new Singleton();

    // Prevent instance creation from other classes
    private Singleton() { }

    public static Singleton Instance { get { return m_Instance; } }

    // Non-static instance members here...
}
and Option 2:
C#
using System.Threading;
sealed class Singleton
{
    private static readonly Singleton m_Instance;

    // Prevent instance creation from other classes
    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (m_Instance == null)
            {
                Singleton temp = new Singleton();
                Interlocked.CompareExchange(ref m_Instance, temp, null);
            }
            return m_Instance;
        }
    }

    // Non-static instance members here...
}


In both cases, m_Instance gets created the first time you call "Instance" - in the first case it is just before executing the function, in the latter it is done within the method, if it hasn't already been created.

Note that with the second option you have to take care of thread-safety yourself. In my example above I've used Interlocked.CompareExchange to achieve this, after checking if the object is null. (This again is not the only way to do this and has its pros and cons - for example, in this case it would still theoretically be possible to have more than one Singleton object created, albeit temporarily, if "Instance" was called in very quick succession from several threads and especially if the constructor of the class was complicated; however, only one of them would ever be returned to any caller).

Therefore the second option necessarily has some extra overhead, which option 1 does not have since the static member needs to be created anyway and the CLR itself takes care of any race conditions. Plus for option 2 every time the Instance member is called thereafter it has to check whether m_Instance is null each time.

If you had some other static members that you could call on the class, then use of the second option may be more appropriate, since in the first option m_Instance would be created as soon as any of them was called. (However, that may be a desired side-effect, so don't rule it out because of that).


There are other pros and cons with each option, but I note there are already so many articles on this I don't intend to go into them in this reply.


Regards,
Ian.

modified 11-Apr-13 13:20pm.

GeneralAn exception thrown inside Singletin's .ctor will be thrown ... Pin
Kelqualyn31-Oct-11 20:44
Kelqualyn31-Oct-11 20:44 
GeneralRe: An exception thrown inside Singletin's .ctor will be thrown ... Pin
Ian A Davidson10-Apr-13 15:33
Ian A Davidson10-Apr-13 15:33 
GeneralRe: An exception thrown inside Singletin's .ctor will be thrown ... Pin
Kelqualyn11-Apr-13 1:27
Kelqualyn11-Apr-13 1:27 
GeneralRe: An exception thrown inside Singletin's .ctor will be thrown ... Pin
Ian A Davidson11-Apr-13 2:04
Ian A Davidson11-Apr-13 2:04 
GeneralReason for my vote of 5 the simplest and because of it the b... Pin
Robert Krzysztof Winkler31-Oct-11 2:03
Robert Krzysztof Winkler31-Oct-11 2:03 
GeneralRe: Reason for my vote of 5the simplest and because of it the b... Pin
Ian A Davidson10-Apr-13 14:37
Ian A Davidson10-Apr-13 14:37 
GeneralThe field should probably be private. Pin
Richard Deeming13-Jul-11 8:11
mveRichard Deeming13-Jul-11 8:11 

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.