A singleton base class to implement the singleton pattern in C#

The singleton design pattern is one of the most controversial pattern. Some people even call it anti-pattern, evil, or stupid. I won’t go into the debate now, but I just want to share something for those who need to use singletons.

Although it is one of the easiest pattern to understand, it is also very easy to code it poorly, leading to unexpected side effects such as poor performance or being not thread-safe.

Jon Skeet has written a very good article describing different implementations of the singleton pattern in C#. He gives a nice example on how you can write a singleton code that is thread-safe and lazy-instantiating. The code is less than 20 lines and you can use it as a template for your singletons.

Since in some projects I have created several singleton objects, it started to get repetitive. Therefore I decided to write a base class based on this pattern as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Globalization;
using System.Reflection;
 
public abstract class SingletonBase<T> where T : class
{
    /// <summary>
    /// A protected constructor which is accessible only to the sub classes.
    /// </summary>
    protected SingletonBase() { }
 
    /// <summary>
    /// Gets the singleton instance of this class.
    /// </summary>
    public static T Instance
    {
        get { return SingletonFactory.Instance; }
    }
 
    /// <summary>
    /// The singleton class factory to create the singleton instance.
    /// </summary>
    class SingletonFactory
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static SingletonFactory() { }
 
        // Prevent the compiler from generating a default constructor.
        SingletonFactory() { }
 
        internal static readonly T Instance = GetInstance();
 
        static T GetInstance()
        {
            var theType = typeof(T);
 
            T inst;
 
            try
            {
                inst = (T)theType
                    .InvokeMember(theType.Name,
                    BindingFlags.CreateInstance | BindingFlags.Instance
                    | BindingFlags.NonPublic,
                    null, null, null,
                    CultureInfo.InvariantCulture);
            }
            catch (MissingMethodException ex)
            {
                throw new TypeLoadException(string.Format(
                    CultureInfo.CurrentCulture,
                    "The type '{0}' must have a private constructor to " +
                    "be used in the Singleton pattern.", theType.FullName)
                    , ex);
            }
 
            return inst;
        }
    }
}

For an example of usage, we will create a singleton class that generates a sequence number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Must seal the class so no sub-classes can be defined.
public sealed class SequenceGeneratorSingleton
    : SingletonBase<SequenceGeneratorSingleton>
{
    // Must have a private constructor so no instance can be created externally.
    SequenceGeneratorSingleton()
    {
        _number = 0;
    }
 
    private int _number;
 
    public int GetSequenceNumber()
    {
        return _number++;
    }
}

Then, a console application will call the sequence generator class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
            .GetSequenceNumber().ToString());  // Print "Sequence: 0"
 
        Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
            .GetSequenceNumber().ToString());  // Print "Sequence: 1"
 
        Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
            .GetSequenceNumber().ToString());  // Print "Sequence: 2"
 
        Console.ReadLine();
    }
}

To recap, in order to create a singleton class using the singleton base class, you need to do the following:

  1. Define a sealed class which derives from SingletonBase<T>, where T is the class name you are defining. It ensures that you cannot create subclasses from this singleton class.
  2. Define a single parameterless private constructor inside the class. It ensures that no instances of this class can be created externally.
  3. Access the class’ singleton instance and public members by calling the Instance property.

I have also included the code in LiquidSilver, which you can view or download from the repository.

  • Mikhail_naumov

    this is something I did too but WHAT IF SequenceGeneratorSingleton has to also inherit from base class e.g. SequenceGeneratorSingleton : Generator
    How would you solve this then?

    • Anonymous

      Hi Mikhail,

      Thanks for your comment.

      As C# doesn’t allow multiple class inheritance, obviously you cannot do it. But there are some possible design alternatives that you can follow:
      1. If the Generator class is abstract, you can convert it to an interface.
      2. Encapsulate the Generator class inside the SequenceGeneratorSingleton class (composition).

      Of course if you really really have to inherit from another base class, then you cannot use this SingletonBase class.

    • http://www.denniland.com/ Denni Gautama

      Hi Mikhail,

      Then it’s a good time to implement the composition instead of inheriting another base class :)

  • ray

    you have a typo on line 5. it should be upper T, not t.

    • http://www.denniland.com/ Denni Gautama

      You’re right, thanks :)

  • Pingback: C# asynch SQL inside singleton and delegates | Jisku.com - Developers Network

  • sung

    Thank you for sharing this code. This helped me a lot.
    But there is a concern regarding this code.

    If one child class of SingletonBase throw exception in its constructor, the exception from the constructor does not get to be shwon. Rather, the exception occurs at { return SignletonFactory.Instance ;} (line 14). This makes it very hard to find where the problem is and debugging.

    Is there any way to have constructor exception not being hidden by SingletonBase Instance?

    • http://www.denniland.com/ Denni Gautama

      Hi sung,

      Because the child class is instantiated by reflection, .NET runtime wraps the actual exception under System.Reflection.TargetInvocationException, which in turn is wrapped under System.TypeInitializationException.

      So, in order for you to get the actual exception, you can modify slightly the code:

      public static T Instance
      {
      get {
      try
      {
      return SingletonFactory.Instance;
      }
      catch (TypeInitializationException ex)
      {
      // ex.InnerException.InnerException is the actual exception in the child class’ constructor
      }
      }
      }