§ October 4, 2006

A Generic Singleton Pattern in C#

I don't know why its never occured to me to implement the singleton pattern as a generic type before. I've always just created the singleton pattern as part of my class (not that we're talking about a lot of coding here), but it occured to me that a singleton could be a lot easier to implement and spot if I used a generic type.

Here is my generic Singleton class:
public static class Singleton<T> where T : new()
{
    static Mutex mutex = new Mutex();
    static T instance;
    public static T Instance
    {
        get
        {
            mutex.WaitOne();
            if(instance == null)
            {
                instance = new T();
            }
            mutex.ReleaseMutex();
            return instance;
        }
    }
}


Now, instead of implementing this same thing in every single class you want to act as a singleton, you simply use the generic definition: Foo.Instance.Whatever turns into Singleton<Foo>.Instance.Whatever.

Now, this doesnt keep you from creating non singleton objects of whatever type you have (there may still be some clever way to do that, but I'm not familiar with it), but it does save you the time of implementing the singleton pattern on singleton objects.
Posted 2 years, 3 months ago on October 4, 2006

 Comments can be posted in the forums.

© 2003 - 2008 NullFX