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
// public method which will be called
public void GetName()
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.
// check whether the instance was there. If it's not there, then create an instance.
if (singleTonObject == null)
singleTonObject = new MySingleTon();
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.
If you have any queries, please feel free to post it here.
Brainstorming Guy aka Venkatarajan A
Really very nice piece of code on Singleton.
If possible give some theory related to singleton.
Keep posting such valuable codes.
Thanks for sharing your knowledge.
Thanks and Regards