In my recent work interviews, I have been asked several times to implement the singleton pattern in c#. In this article I will try to guess what the interviewers wanted to hear …

Understanding the Problem

The first thing the candidate needs to know is what is the singleton pattern. The interviewers were kind enough to explain what is the singleton pattern, by quoting from Wikipedia:

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Let’s see what the requirements from the singleton class are:

  • The class should provide a mechanism to create one and only one object.
  • The class should provide a mechanism to access this single object.

The Naive Solution

The first requirement – the mechanism to create one and only one object – can be achieved by deciding that the singleton class will be responsible to creating its single instance and restricting the instantiation of the class by entities of other classes (in their constructors, methods, field’s initializers, property’s getters and setters and their static counterparts).

singleton design pattern agreement

Luckily, C# language allows us to restrict access to constructors, methods, properties and fields. By declaring the singleton constructor as private, the only entities that can create this class are its members. The following code snippet demonstrates this restriction.

c# supports restricted access
class Singleton {
    // When we declare the class constructor as private, no other class can instantiate the class.
    private Singleton() {
    }
    public static void Main(string[] args) {
    }
}
class OtherClass {
    // when uncommenting the Singleton class instantiation in the following entities ,
    // the compiler will complain that Singleton constructor is inaccessible in the
    // current context.
    public OtherClass()        { /* Singleton singleton = new Singleton(); */ }
    static OtherClass()        { /* Singleton singleton = new Singleton(); */ }
    public void Method()       { /* Singleton singleton = new Singleton(); */ }
    static void MethodS()      { /* Singleton singleton = new Singleton(); */ }
    public int Property  { get { /* Singleton singleton = new Singleton(); */ return 1; }
                           set { /* Singleton singleton = new Singleton(); */           } }
    static int PropertyS { get { /* Singleton singleton = new Singleton(); */ return 1; }
                           set { /* Singleton singleton = new Singleton(); */           } }
    /* public Singleton _field  = new Singleton(); */
    /* static Singleton _fieldS = new Singleton(); */
}

We also need the class to create one and only one instance. The obvious solution is to declare a public readonly static field and initialize it with new instance of the class.

This will ensure that only one object will be created since the static fields initializers are executed at most once in a given application domain. The other classes will access this object via this static field since it is public but cannot change its contents since it is readonly.

singleton #1
class Singleton {
    private Singleton() {
        System.Console.WriteLine("Singleton");
    }
    public void DoWork() {
        System.Console.WriteLine("DoWork");
    }
    public static readonly Singleton Instance = new Singleton();
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main");
        Singleton.Instance.DoWork();
    }
}

This seems to work, we have a basic solution which fulfills the basic requirements of the singleton pattern. But is it the solution the interviewer wants to hear? When we run the program, we get the following output:

singleton #1 output
Singleton
Main
DoWork

The object is created before it is needed. This may impact the performance of the program if the instantiation consumes precious execution time and memory resources.

We need another approach. :-)

Solution 2 - Lazy without thread safety

The following class allows other classes to access its single object via static property. In the static property, we will create the object if it does not exist and return the single object.

singleton #2
class Singleton {
    private Singleton() {
        System.Console.WriteLine("Singleton");
    }
    public void DoWork() {
        System.Console.WriteLine("DoWork");
    }
    public static Singleton Instance {
        get {
            if (_instance == null) {         // <== A
                _instance = new Singleton(); // <== B
            }
            return _instance;
        }
    }
    private static Singleton _instance = null;
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main");
        Singleton.Instance.DoWork();
    }
}

When we run the program, we get the following output:

singleton #2 output
Main
Singleton
DoWork

This seems to work but now there is no guarantee that only one object will be created. In multi-threaded programs, there can be situations where the object will be created several times.

Suppose one thread wants to access the single object via the static property when the object does not exist yet. The thread executes the if statement (A) and finds out the object does not exist yet. It starts to create the object (B), but then gets suspended. Now another thread tries to access the single object via the static property. Now the second thread executes the if statement (A) and finds out the object does not exist yet (since the first thread did not finish to create the object). Eventually, the 2 threads will create an object.

The following program demonstrates this problem:

singleton #2 - tester
using System.Threading;
class Singleton {
    private Singleton() {
        System.Console.WriteLine("Singleton : Start");
        if (_first ) {
            _first = false;
            Thread.Sleep(5000);
        }
        _count++;
        System.Console.WriteLine("Singleton End. There are {0} objects", _count);
    }
    public void DoWork(int xx) {
        System.Console.WriteLine("DoWork {0}", xx);
    }
    public static Singleton Instance {
        get {
            if (_instance == null) {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
    private static Singleton _instance = null;
    private static bool _first = true;
    private static int _count = 0;
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main Started");
        Thread s1 = new Thread(() => Singleton.Instance.DoWork(1)); s1.Start();
        Thread s2 = new Thread(() => Singleton.Instance.DoWork(2)); s2.Start();
        s1.Join(); s2.Join();
        System.Console.WriteLine("Main Ended");
    }
}

When we run the program, we get the following output:

singleton #2 - tester output
Main Started
Singleton : Start
Singleton : Start
Singleton End. There are 1 objects
DoWork 1
Singleton End. There are 2 objects
DoWork 2
Main Ended

We need another approach. :-)

Solution 3 - lazy and thread safe - version 1

Luckily, csharp has a simple construct to synchronize threads using the lock block. The lock block guarantees that only one thread will execute the code inside it at a given time:

singleton #3
using System.Threading;
class Singleton {
    private Singleton() {
        System.Console.WriteLine("Singleton");
    }
    public void DoWork() {
        System.Console.WriteLine("DoWork");
    }
    public static Singleton Instance {
        get {
            lock (_locker) {                    // <== A
                if (_instance == null) {        // <== D
                    _instance = new Singleton();// <== B
                }
                return _instance;
            }                                   // <== C
        }
    }
    private static Singleton _instance = null;
    private static object _locker = new object();
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main");
        Singleton.Instance.DoWork();
    }
}

Now there is guarantee that only one object will be created.

Suppose one thread wants to access the single object via the static property when the object does not exist yet. The thread tries to acquire the lock (A) and succeeds (since no other thread have the lock). It starts to create the object but then get suspended (B). Now other thread wants to access the single object via the static property, it tries to acquire the lock (A), fails (since the first thread already acquire the lock) and therefore get suspended. Only when the first thread finishes to create the object and releases the lock (C) - The thread get resumed - but now, the object already exist and there is no need to create the object (D).

The output of the program is as shown below:

singleton #3 tester output
Main Started
Singleton : Start
Singleton End. There are 1 objects
DoWork 1
DoWork 2
Main Ended

It seems to solve the problem. But as we know “All magic comes with a price”, every time we access the single object, we request a lock. Since locking pieces of code takes some time – this solution has performance impact. Can we improve it?

Solution 4 - lazy and thread safe - version 2

The synchronization problem occurs only when the object does not exist yet. When the object exists, we can simply return _instance static field. Using this observation, our next approach is to request the lock only when needed – when we create the single object.

singleton #4
class Singleton {
    private Singleton() {
        System.Console.WriteLine("Singleton");
    }
    public void DoWork() {
        System.Console.WriteLine("DoWork");
    }
    public static Singleton Instance {
        get {
            if (_instance != null) {
                return _instance;
            }
            lock (_locker) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
                return _instance;
            }
        }
    }
    private static Singleton _instance = null;
    private static object _locker = new object();
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main");
        Singleton.Instance.DoWork();
    }
}

We still need to lock the piece of code that creates the object. Can we have a better solution?

Solution 5 - lazy and thread safe - version 3

In the first solution of the problem, the object has been created before it was needed. If we enclose this class in outer class and provide static property to access the object – the object will be created only when needed since static fields initializers are executed at most once in a given application domain when the class is first accessed.

singleton #5
class Singleton {
    public class Inner {
        private Inner() {
            System.Console.WriteLine("Singleton");
        }
        public void DoWork() {
            System.Console.WriteLine("DoWork");
        }
        public static Inner _instance = new Inner();
    }
    public static Singleton.Inner Instance {
        get {
            return Inner._instance;
        }
    }
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main");
        Singleton.Instance.DoWork();
    }
}

And this will produce the desired output without locks:

singleton #5 output
Main
Singleton
DoWork

Solution 6 - lazy and thread safe - version 4

csharp 4.0 introduces the Lazy<TT> for lazy instantiation as part of BCL. This class allow to defer the instantiation of an TT object until the time it is needed to save memory and execution time.

When the Value property of Lazy<TT> is first accessed - the TT object is created using initialization method given in the constructor or by the default constructor of TT. In the default mode , the initialization is thread safe - locks are used to ensure that only a single thread can initialize a TT instance - similar to solution 4.

We will use this class in current solution:

singleton #6
class Singleton {
    private Singleton() {
        Console.WriteLine("Singleton");
    }
    public void DoWork() {
        Console.WriteLine("DoWork");
    }
    public static Singleton Instance {
        get {
            return LazyInstance.Value;
        }
    }
    private static readonly Lazy<singleton> LazyInstance = new Lazy<Singleton>( () => new Singleton() );
}
class Program {
    static public void Main() {
        System.Console.WriteLine("Main");
        Singleton.Instance.DoWork();
    }
}

Summary

We have seen 6 approaches for solving the problem. How does the interviewer evaluate your solution?

  • Whether your solution is correct.
  • Whether you can explain the solution.
  • Whether you understand and keep up with the environment you are working with
  • Whether you foresee issues that may arise when using your solution.
    • Whether your solution is thread safe.
    • Whether your solution ensures that single object is created only when needed to save memory and execution time.
    • Whether your solution allows accessing the object as fast as possible.