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

Tagged as

Simple Singleton Pattern in C#

, 31 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Here is an alternate sample of "Singleton" Pattern. And I hope it is easier to understand.public class MySigleton{ private static MySigleton instance; private MySigleton() { } public static MySigleton InstanceMySigleton { get { if...
Here is an alternate sample of "Singleton" Pattern. And I hope it is easier to understand.
public class MySigleton
{
    private static MySigleton instance;
 
    private MySigleton() { }
 
    public static MySigleton InstanceMySigleton
    {
        get
        {
            if (instance == null)
            {
                instance = new MySigleton();
            }
            return instance;
        }
     }
}
Singleton with Multithreading
public sealed class MySigleton
{
   private static volatile MySigleton instance;
   private static object syncRoot = new Object();
 
   private MySigleton() {}
 
   public static MySigleton InstanceMySigleton
   {
      get
      {
         if (instance == null)
         {
            lock (syncRoot)
            {
               if (instance == null)
                  instance = new MySigleton();
            }
         }
 
         return instance;
      }
   }
}

License

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

Share

About the Author

RaisKazi
Technical Lead
United States United States
No Biography provided

Comments and Discussions

 
GeneralMore aspects of singleton pattern PinmemberPeace ON20-Jul-13 0:40 
GeneralRe: I would be ok with your Vote, but my updated approach is thr... PinmemberRaisKazi1-Nov-11 3:35 
GeneralRe: Unfortunately this is the same as this articles original wit... PinmemberJayne Dale1-Nov-11 0:23 
GeneralReason for my vote of 1 This is not Thread-Safe. PinmemberLuchoStudio1-Nov-11 3:31 
GeneralRe: I would be ok with your Vote, but my updated approach is thr... PinmemberRaisKazi1-Nov-11 3:36 
GeneralReason for my vote of 1 Not thread safe... PinmemberJayne Dale31-Oct-11 12:39 
GeneralRe: Appreciate your Feedback. Please have a look at updated Alt... PinmemberRaisKazi31-Oct-11 18:51 
GeneralNot thread safe... PinmemberJayne Dale31-Oct-11 12:38 

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 | Mobile
Web01 | 2.8.140827.1 | Last Updated 1 Nov 2011
Article Copyright 2011 by RaisKazi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid