Creating Singleton class in C#


In many of the cases, we come accross situations where we want to create only one instance of a class. And use it throughout the application. As a programmer we have to take care of that from the code itself. Let's take a look at this step by step.

We will create a class MySingletonClass in such a way that it can be instantiated only once.

    public class MySingletonClass
    {
        //This will create a static instance of the class MySingletonClass
        private static MySingletonClass instance;

        //Private constructor
        private MySingletonClass() { }

        public static MySingletonClass Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MySingletonClass();
                }
                return instance;
            }
        }

        public void DoWork()
        {
            Console.WriteLine("I am going for lunch");
        }
    }

So we are done with the class definition. Now let's start creating it's instances.

    class Program
    {
        static void Main(string[] args)
        {
            MySingletonClass objMySingleton = MySingletonClass.Instance;
            MySingletonClass objMySingleton2 = MySingletonClass.Instance;

            objMySingleton.DoWork();

            Console.ReadLine();
        }
    }

If you debug this code and put a break-point at get of Instance, you will notice that the object creation statement will get executed only once for the first object. For later requests the program will serve the existing one.

Now, if by mistake or intentionally, someone else tries to create an instance of MySingletonClass in traditional way as;

MySingletonClass objMySingleton = new MySingletonClass();

Our private constructor will not allow this to be compiled due to protection level.
So our class can be instantiated only once from anywhere in the application and the instance can be shared.


No comments:

Post a Comment