C# - 19 - A DRY thread-safe singleton

[C# 3.5]

The Singleton pattern, as often described, is not thread-safe. For more details check out "Implementing the Singleton Pattern in C#".

However, an application may require a number of different singletons and thus the boilerplate code to make a thread-safe singleton will get repeated time and time again. This breaks the DRY principle ("Don't Repeat Yourself). The solution is a singleton base class from which singleton classes can inherit. Here is the code for SingletonBase.cs

To implement you just have to inherit from this …

(Bear in mind that the constructor needs to be parameterless.)

.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License