Jitesh Byahut 7/9/2014 2814

Singleton Class In C#

The class which allow to create only one object is known as Singleton class.

Lazy instantiation

Lazy instantiation avoids creating unnecessary singletons when application starts. Below examples showing [Gamma95] Design-Patterns.

class Singleton

{

        private static Singleton instance;      

 

        private Singleton()

        {

            Console.WriteLine("Singleton object created");           

        }

 

        public static Singleton CreateObject

        {

            get

            {

                if (instance == null)

                {

                    instance = new Singleton();

                }

                return instance;

            }

        }

 

}

class Program

{

        static void Main(string[] args)

        {          

            // Create instance of Singleton Class

            Singleton obj = Singleton.CreateObject;                       

        }

}

If you create more than one instance of singleton class then it's create a object at first time and when you try to create second instance then it simply return previous created object, means second time it's not creating any new instance. So finally it it's create only one instance does not matter how many time you try to create instance.

static void Main(string[] args)

{

            // Create instance of Singleton Class

            Singleton obj = Singleton.CreateObject;

           

            Singleton obj1 = Singleton.CreateObject;

          

}

you consider output of above example, it show only one instance create message, means at second time it will not create any object.

Output:

static void Main(string[] args)

{

            // When you try to create object using new keyword then it will

            // show an error

           

            // Incorrect way to create object of Singleton class

            Singleton obj = new Singleton();

            // error

            // 'Singleton.Singleton()' is inaccessible due to its protection level

            

}

Above example provides you to implement singleton pattern but that have some disadvantage in case of multithreading. Suppose more than one threads are executes at same time and enter to CreateObject property then on that time more than one instance may be created. So, to provide type safety in multithreading environments use Static Initializer or Double-Check Locking method.

Static initialization

In C#, CLR provides Static Initialization approach, which is not required any additional code to handle multithreading environment.

public sealed class Singleton1

{

        private static readonly Singleton1 instance = new Singleton1();

       

        private Singleton1()

        {

            Console.WriteLine("Singleton object created");           

        }

 

        public static Singleton1 CreateObject

        {

            get

            {

                return instance;

            }

        }

}

Multithreaded Singleton

Here we are using Double-Check-Locking [Lee99] idiom to keep separate threads from creating new instances of singleton class at same time.

public sealed class Singleton2

{       

        private static volatile Singleton2 instance;

        private static object objlock = new object();

 

 

        private Singleton2()

        {

            Console.WriteLine("Singleton object created");

        }

 

        public static Singleton2 CreateObject

        {

            get

            {

                if (instance == null)

                {

                    lock (objlock)

                    {

                        if (instance == null)

                        {

                            instance = new Singleton2();

                        }

                    }

                }

                return instance;

            }

        }

 

}


Please give your feedback for improving this page