Singleton remarks

posted @ Friday, October 1, 2004 6:43 PM

 

There are many different ways to skin the Singleton cat, well; at least there are slight variations of it anyway. However the following way is more efficient than using volatile because of performance implications.

public sealed class Singleton
{
private Singleton(){}
private static Singleton value;
private static object syncRoot = new Object();

public static Singleton Instance
{
get
{
if(Singleton.value == null)
{
lock(syncRoot)
{
if(Singleton.value == null)
{
Singleton s = new Singleton();
System.Threading.Thread.MemoryBarrier();
Singleton.value = s;
}
}
}
return Singleton.value;
}
}
}