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

Labels

.net .Net Instrumentation logging .net localization Agile amazon amazon elasticache amazon services AppDomain Application Domain architecture asp ASP.Net authentication authentication mechanisms Byte order mark c# cache cdata certifications class classic mode cloud cloud computing cluster code-behind Combobox compilation Configuration providers configurations connection connectionString constructors control controls contructor CSV CTS .net types conversion database DataGridView DataSource DataTable DataType DBML delegates design pattern dispose double encoding Entity framework Events exception handling expiry fault contracts fault exceptions function pointers functions generics help HostingEnvironmentException IIS inner join instance management integrated mode javascript join left outer join LINQ LINQ join LINQ to SQL memory leak methods microsoft modes in IIS MSIL multiple catch blocks no primary key Nullable Osmos Osmotic Osmotic communication Osmotic communications page events page life cycle partial class PMI preserve precision points private contructor ProcessExit Project management properties property protect connectionString providerName providers query regular expression repository Responsive Web Design return type run-time RWD Saas self join session session expiry sessions singelton singleton pattern software as a service source control system SQLMetal string toolstrip ToolStrip controls ToolStripControlHost tortoise SVN ToString() try catch finally update wcf web application web design web site web.config where-clause xml