CODECUBE VENTURES

Generic Singleton in C#

Ever since they announced that C# 2.0 was going to have generics, I have been struggling with trying to find a reason to actually use generics. I mean, I know that they're fantastic for collections, but those are already implemented in the next framework. So I was trying to figure out when they would be useful in a custom coding situation. At first, I thought that I'd be able to use it to make generic functions for mathematical algorithms so you could use float, int, double, whatever. Unfortunately, after I got a copy of vs2005 at VSLive, I realized that it wasn't going to be quite that easy ... other people agree.

I was reading Troy Gilbert's blog when I saw a snippet of c++ code that gave me an idea ... Generic Singleton!

Now, before you destroy my singleton implementation, I know that this isn't particularly thread-safe. But that's ok because you can find many resources on making singletons thread safe.

The Singleton

public class Singleton<T> where T: new()
{
private Singleton()
{}

private static T mInstance = default(T);

public static T Instance
{
get
{
if (mInstance == default(T))
{
mInstance = new T();
}

return mInstance;
}
}
}

Notice a few things. The generic type is constrained so that it must have a constructor. Also, the private instance is intialized wtih default(T). This is because you could use this (as retarded as it sounds) for a value type such as an int so null wouldn't work for that. Despite the fact that I could have sworn it was possible. Either way, the compiler yelled at me for setting mInstance = null so who am I to argue ;-) (Edit: I re-read eric's article, and I guess I might have been able to use the nullable type declaration syntax T? mInstance = null;, but default(T) works just as fine)

A simple test with a few test classes shows you how this would be used

public class Program
{
[STAThread]
static void Main(string[] args)
{
Singleton<Test1>.Instance.Value = "Hi";
Singleton<Test2>.Instance.Number = 13;

Console.WriteLine("Test1 value: {0}",
Singleton<Test1>.Instance.Value);

Console.WriteLine("Test2 number: {0}",
Singleton<Test2>.Instance.Number);
}

private class Test1
{
public string Value;
}

private class Test2
{
public int Number;
}
}

So what's the drawback? unfortunately, the type that you will be using as a singleton must have a public constructor since it must be instantiated by the generic Singleton class. I personally would be ok with using this in my own project, but I don't know how appropriate it would be use this in a public facing API. Oh well, time will tell ... please leave feedback on this blog post if you have any ideas on how this could be implemented better. Or email me: jmartinez {@t} codecube . net

Latest post: Digging Up the First Version of CodeCube

See more in the archives