Generic Singletons

03/21/08

Generic Singletons

It’s amazing what you can do with generics in C#. Here’s one way to implement a generic Singleton:

Code:

public abstract class Singleton<TThis>
    where TThis : Singleton<TThis>, new()
{
    static Singleton()
    {
    }
 
    public static TThis Instance
    {
        get { return _Instance; }
    }
 
    private static readonly TThis _Instance = new TThis();
}

If you’re wondering about the need for an empty static constructor, see http://www.yoda.arachsys.com/csharp/singleton.html.

Non-abstract descendants should be sealed:

Code:

public sealed class Child : Singleton<Child>
{
}

One downside is that you do need a public constructor (implicit in the example), so it is possible for clients to bypass the Singleton instance.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.