Introduction

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance – as otherwise, the second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily – i.e. that the instance isn’t created until it is first needed.

There are various ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to an entirely lazily-loaded, thread-safe, simple and highly performant version.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing – if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn’t known until runtime.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Let’s start with a quick example of a singleton class.

namespace betechnical
{
    
    public class Singleton
    {
        ///
        /// Private constructor to protect the instance of class
        ///
        private Singleton(){ }
        private static Singleton _instance;
        private static readonly object Sync=new object();

        public static Singleton Instance()
        {
            //Check if instance is null then only enter to the block
            if (_instance == null)
            {
                //Check if another thread is alreayd accessing
                lock (Sync)
                {
                    //Check if instance is already created by previous thread
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }

    }
}