Clean implementation of static class instances

Sometimes an application requires a single static instance of a class for the duration of the life of the application. This is typically done by following the Single Design Pattern. One way to demonstrate such an implementation in C# is as follows,


public class Dog {

private static Dog m_Instance = null;

public static Dog Instance {

get {
if (m_Instance == null) {
m_Instance = new Dog();
}
return m_Instance;
}
}

// Dog implementation follows ...
}

However, can we do better? For instance, what if we have a number of classes which should have a single static instance? We would have to repeat the above code within each class to provide an Instance property. I was recently presented with this exact problem and realized that there is something quite common in the Instance implementation.

In fact, just about the entirety of the code is common except the invocation of the constructor for a particular type. Using generics and reflection we can abstract the Instance property by providing a single abstract class that implements the Instance property for any class type with a default constructor.

The following is a neat implementation of just that.


public abstract class StaticInstance<T> where T : class, new()
{
private static T instance = null;

public static T Instance
{
get
{
if (instance == null)
{
instance = Activator.CreateInstance<T>();
}
return instance;
}
}

}

Now, we can implement Dog as follows,


public class Dog : StaticInstance<Dog> {

public Dog() { ... }

// Dog implementation follows ...

}

which gives the Dog class the Instance property. Neat!