Singleton pattern is a simple design pattern in software practice and sometimes considered as an anti-pattern due its tight coupling nature.
A very simple non thread safe implementation of the Singleton pattern would be like this.
Singleton non thread safe
Run the above class using Main method shown below, you can notice Singleton constructor is called twice by the both threads, since it is not thread safe. ( You can use the same Main methid implementation for all 3 Singleton implementations)
Main method implementation
Singleton thread safe
Making the above implementation to a thread safe code is not a complex task, we can use our same old locking technique.
The above is a perfect Singleton implementation in C#. But is there any other way that we can have the Singleton behavior without compensating our performance into locking. Because locking is a performance drop for sure.
Singleton C# way – The trendy way
This is a neat and a trendy way to implement the Singleton.
We do not use locks in this implementation and it is very fast yet purely thread safe.
The magic is, static constructor.
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
To remeber simply you can think that the static constructor is called when the class is loaded.
More about static constructors in this MSDN article.