Singleton Pattern

Singleton is a software design pattern in which it restricts instantiation of class to just one instance and provides a global point of access to it.

First, lets start with simple Singleton pattern with the example below -

Here we have sealed class SimpleSingleton and it is sealed because we don't want any other class to inherit this.

In this class we have one private static variable "_instance" of type "SimpleSingleton" and we have public static property "Instance" with only Get.

This property "Instance" sets the value of private static variable "_instance" by creating new instance only when it is null. There after whenever this property is accessed then it will always return the same instance which was created first time.

If you have this type of patter implementation in stand alone desktop application developed for single user then this implementation looks OK. But think for a second if same code is implemented in a web application? We will run into issue of multiple threads.

What if 2 or more requests hits server at same time and all threads tries to execute above code at same time? In that case we may end up with more than one instance of "SimpleSingleton" class and that defeats the idea of this pattern.

Hence, we have Thread safe Singleton pattern. Again, many engineers have come with various ideas to make it Singleton thread safe and at the same time make sure only one instance is created. Performance has to be factored in before we decide on any particular implementation method.

Let's look into Thread safe Singleton. (also Lazy instantiation)

In the above code, please observe where instantiation of singleton class is happening.

Yes, it you can see "new ThreadSafeSingleton()" inside "Nested" class. This new instance is assigned to a internal static readonly instance of type "ThreadSafeSingleton".

If we go up the class hirarchy and see that property "Instance", we can see instantiation is triggered here to the static member of the nested class. Hence it is lazy instantiation.

But still above code has some grey area and that is why do we have Nested() constructor method? Well short answer is to tell c# compiler that to not mark type as beforefieldinit. Absence of this constructor means, class can be marked as beforefieldinit and have its type initializer invoked at any time before the first reference to a static field in it.