Thread Safe Singleton Design Pattern in .Net C# (Utilizing the C# Properties Efficiently)

Aj Jadoon
Peaceful Programmer
2 min readOct 21, 2018

Singleton pattern is one of the most easiest design pattern which almost every developer knows about. In theory this pattern is about allowing only one instance of a class.

We are not going to talk about pros and cons or usage of this pattern in this article. What we are going to talk about is that how to make this simple pattern thread safe and how understanding and utilizing C# properties properly can save us time

Yes Single Instance as Lonely as this

Let’s start with the simplest example of Singleton and then we will discuss that what’s wrong with it and how can we improve

Important Rule: Private Constructor

As you can see from the example it is a very simple code. We just have to make the constructor private so that class cannot be instantiated externally. And internally we have applied a check to instantiate it only once.
But there is one problem with this simple code. Let’s say that if two different threads are running then things can go wrong. What if one thread is almost about to create the instance and while the other thread passes the check of instance==null?

Making Code Thread Safe Classical Way

Here i am using the Jon Skeet example for making Singleton thread safe

So now we are using mutex(padlock) to make sure that only one thread is allowed to run. But the problem is that we will be locking it each time which doesn’t seem right. Well that can be fixed but we will not go into that detail as we have more elegant and simple solution.

Making Code Thread Safe With Static Initalizers and Properties, The Modern Way

Congratulations, You have implemented a thread safe Singleton pattern . But how? Because static initializers are thread safe, so CLR will take care for keeping it thread safe. We are using expression bodied static read only get property here i.e

public static Singleton Instace => new Singleton();**Not valid Update**

It is equivalent to using

public static Singleton Instace { get; } = new Singleton();

And Also Equivalent to using

As you can see that properly using properties can save lines of code and make code more readable. Just remember that by default the properties will be read-only if you use like above and static initialization is thread safe

Don’t forget to share your thoughts and yes also read this interesting article by Jon Skeet

**Update 02-Jan-2019: I noticed that it does not behave as Singelton

Code Available At Github

--

--

Aj Jadoon
Peaceful Programmer

Full Stack Dot Net Software Developer and Ex- AWS Certified Developer currently residing in Sweden. Contact me on https://www.linkedin.com/in/abduljaliljadoon/