C# Singleton Pattern

Singleton Pattern in C#

This piece of code will explain how to implement the Singleton pattern when we create a class.

    public class MySingleTon
        private static MySingleTon singleTonObject;
        // private constructor. This will avoid creating object using new keyword
        private MySingleTon()

        // public method which will be called
        public void GetName()
            Console.WriteLine("Brainstorming Guy");
        public static MySingleTon CreateInstance()
            // this object will be used with lock, so that it will be always one thread which will be executing the code
            object myObject = new object();
            // put a lock on myObject. We won't be able to use singleTonObject becuase it will be null. lock is to make the object thread safe.
            // lock can't be worked with null objects.
            lock (myObject)
                // check whether the instance was there. If it's not there, then create an instance.
                if (singleTonObject == null)
                    singleTonObject = new MySingleTon();
            return singleTonObject;

You can get an instance and you can make a call as given below.

            MySingleTon myObject = MySingleTon.CreateInstance();
            myObject = MySingleTon.CreateInstance();

When you execute the above piece of code, you can note that when the first time CreateInstance method is called, it will create an instance. But when you make a second call, it will check whether instance exists there and if it exists, it will return the same instance.
I placed comments in almost all the lines of the singleton class.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: