in Development

Singleton Pattern

Yesterday I was viewing a video (Spanish) that explains about how to implement the Singleton pattern in .NET. After some implementations the video ends up showing the best way to have a thread safe implementation of the singleton pattern.

The problem is the video ends saying that the next two implementations are exactly the same on a functional level, which is not completely true.

Implementation 1

Implementation 2

The second implementation is correct, since it shows how you can avoid the lock while creating the object instance of the Singleton class. The reason why this is thread safe is because .NET guarantees that the Type Constructor (or Type Initializer on the ECMA standard) is executed only once per AppDomain and is thread-safe.

Regardless both of them are thread-safe, the difference is that the first one is lazy loaded while the second one is eager loaded. In order to implement the singleton pattern using a lazy loaded version and still take profit of the Type Constructors, you need to add a container for the object instance of Singleton2. Doing this the Type Constructor will only be initialized when you access the property (or any other member making reference to it). Below you can see the correct implementation for it.