Implementing singleton inheritable class in C#

Ignoring the usual "Don't use a Singleton, look at your design." arguments, you could conceivably implement one as thusly (assuming your derived classes have default constructors):

public abstract class Singleton<T> where T : class, new()
{
    private static T _instance;

    public static T GetInstance()
    {
        if(_instance == null)
            _instance = new T();
        return _instance;
    }
}

And derive like this:

public class SingletonA : Singleton<SingletonA> { /* .... */ }
public class SingletonB : Singleton<SingletonB> { /* .... */ }

But, I really don't advocate this singleton approach personally. They do have their (rare) uses, but they can turn out to be more of a pain in the bum - turning in to glorified global variable containers.

Also, be mindful of thread-safety.


My question is: Is there another way to implement a Singleton class in C# ensuring that derived class are also singleton?

Well, you could have some sort of check within the constructor that:

  • The actual type of this is sealed
  • The actual type of this is a direct subclass of Singleton
  • No other instance of that type has been created (by keeping a HashSet<Type>)

However, it seems rather pointless. What is your base class actually meant to achieve?

The singleton pattern is easy to implement properly (which your example doesn't, by the way - it's not thread safe) so why have the base class? The base class itself wouldn't be a singleton (there would potentially be many instances - one per subclass) so what's the benefit?

It seems to me that "I'm a singleton for the actual type of the object" isn't an appropriate basis for inheritance in the first place, and frankly I'd try to avoid the singleton pattern as far as possible anyway.

If you really want a base class, it should be because there's some common functionality that all the subclasses naturally inherit. That's unlikely to be inherently to do with whether those subclasses are singletons.