Friday, 8 May 2009

Generic Singleton

I've no idea why a generic singleton class is not available in the .Net framework, so I had to write my own. Here's the result.
public class Singleton<T> where T : Singleton<T>
{
private static object instanceLock = new object();
private static T value;

public static T Value { get { return GetValue(); } }

private static T GetValue()
{
lock (instanceLock)
{
if (value == null)
{
value = (T)Activator.CreateInstance(typeof(T), true);
}
}
return value;
}
}

To use it define a sealed subclass with a private constructor and away you go. For example
public sealed class ContextSingleton : Singleton<ContextSingleton>
{
private ContextSingleton() { }
}

If you have got a few extra minutes, it might be worth checking to ensure that the subclass is sealed and has no public constructors at runtime in the GetValue() method.

No comments:

Post a Comment