An obvious singleton implementation for .NET?
Solution 1:
This is the canonical, thread safe, lazy Singleton pattern in C#:
public sealed class Singleton
{
Singleton(){}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() {}
internal static readonly Singleton instance = new Singleton();
}
}
Solution 2:
To prevent from having to copy the singleton code, you could make the type generic, as such:
public abstract class Singleton<T>
where T: class, new()
{
public static T Instance
{
get { return Nested.instance; }
}
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() { }
internal static readonly T instance = new T();
}
}
public sealed class MyType : Singleton<MyType>
{
}
class Program
{
static void Main()
{
// two usage pattterns are possible:
Console.WriteLine(
ReferenceEquals(
Singleton<MyType>.Instance,
MyType.Instance
)
);
Console.ReadLine();
}
}