Friday, 19 December 2008

A generic singleton - Part 2

Here is the critique and why there is a better solution to the article: A generic singleton

Well, it isn't really singleton - since you can't control T, there can be as many T instances as you like.

The code does check for non-public constructors, which is good. However, this is a check which is only performed at execution time - there's no compile-time check, which is a strike against it. It also relies on having enough access to call the non-public constructor, which adds some limitations.

In addition, it doesn't prohibit internal constructors - so you can end up with non-singletons.

There is an excellent article on singletons at http://www.yoda.arachsys.com/csharp/singleton.html

Here are two proper implementations:

public sealed class Singleton
{
    static readonly Singleton instance = new Singleton();
 
    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }
 
    Singleton()
    {
    }
 
    public static Singleton Instance
    {
        get { return instance; }
    }
}

Or simply:

public
class Singleton
{
    private static Singleton _instance = new Singleton();
    private Singleton() {}
    public static Singleton Instance { get { return _instance; }}
}

Both of these classes removes the need for locking, as a static constructor is thread safe.