Singeton in C#
Since I used to be a Java programmer, I used to write singletons in c# like this:
public class MySingleton { private static MySingleton instance; public static MySingleton Instance { get { if (instance == null) { lock(typeof(MySingleton)) { if (instance == null) { instance = new MySingleton(); } } } return instance; } private MySingleton() { // do init } }
Until I wanted to show a colleague the data & object factory site, a design patterns website specifically targeted at c# development.
Aparently, as stated here, there is a more elegant way of implementing a thread-safe, lazy instantiated singleton in .NET. You can just declare your instance field to be static and readonly, assign a new instance at the line where you declare it and it will be lazy-instantiated at runtime.
Like this:
public class MySingleton { private static readonly MySingleton instance = new MySingleton(); public static MySingleton Instance { get { return instance; } } private MySingleton() { // do init stuff } }
Looks a lot better. But do both code snippets behave in exactly the same way? Before testing the differences myself, I decided to give my good friend Google a spin, and it came up with this interesting article by Alois Kraus.
Aparently it would not be wise to just convert all singletons in my projects to the ‘elegant’ .NET way :)
Thursday 28 Sep 2006 | Guy Mahieu | .net(t) , c#(t) , design patterns(t)
There is offcourse a functional difference between these 2 ways of implementing a singleton; the first one uses lazy initialization, while the 2nd one does not.
Although you say it is lazy instantiated… how is it done ? You instantiate an instance of the object at declaration ?
Well, according to the .NET specific pattern description on dofactory they should functionally be the same. This surprised me as well, which is why I looked for more detailed information.
The article by Alois Kraus sheds a different, and more detailed, light on this. If you add a static constructor, you will have lazy initialization; if you don’t, your singleton instance will be initialized when the class is loaded regardless of whether it is used or not.
Here is some interesting info concerning the Singleton pattern: http://www.yoda.arachsys.com/csharp/singleton.html