//First version - not thread-safe
//Bad code! Do not use it!
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Example 2 for Simple thread safety via locking:
//Second version - simple thread-safety
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton() { }
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Example 3 for Double-checked locking:
//Third version - attempted thread safety using double-check locking
// Bad code! Do not use it!
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Example 4 for Safety through initialization:
//Fourth version - not quite as lazy, but thread-safe without using locks
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton() { }
private Singleton() { }
public static Singleton Instance
{
get
{
return instance;
}
}
}
Example 5- Safe and fully lazy static initialization: