We are often required to implement the singleton pattern in our code. While doing this yet again I thought there must be a generic way to do this and I came up with the following code …

public static class Singleton<T> where T : class, new()
{
   private static volatile T _instance;
   private readonly static object _lockObj = new object();
 
   public static T Instance
   {
       get
       {
           if (_instance == null)
              lock (_lockObj) if (_instance == null) _instance = new T();
 
           return _instance;
       }
  }
}



This allows you to use any class as a singleton …

var mySingleton = GenericSingleton<MySingleton>().Instance;



It’s not perfect … there is nothing stopping the developer from creating a new instance of the class which breaks the singleton pattern. Doing it the normal way makes it impossible to create more than one instance of a class but this way allows the flexibility to use a class as a singleton even if it’s not implemented that way and also allows a mix of singleton and instances of the same class.

In any event it makes interesting use of generics and I just thought it was cool so I thought I’d share :)