Singleton Design Pattern in C#

  • Only one instance of object is created.
  • Is a creational design pattern which makes sure that you have one single instance of a particular class in the duration of your runtime, and provides a global point of access to the single instance.
public class Singleton
    {
        private static Singleton instance;

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
  • The main disadvantage of this implementation is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more than one instance of the Singleton object may be created.

public sealed class Singleton
    {
        private static volatile Singleton instance;
        private static object syncRoot = new Object();

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }

                return instance;
            }
        }
    }
  • The above approach ensures that only one instance is created and only when the instance is needed.
  • Also variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks