Click here to Skip to main content
13,860,468 members
Click here to Skip to main content
Add your own
alternative version


146 bookmarked
Posted 5 May 2006
Licenced Ms-PL

Generic Singleton Pattern using Reflection, in C#

, 9 Jun 2009
Rate this:
Please Sign up or sign in to vote.
Use a generic class to create all your Singletons.


This article presents a generic class that uses Reflection to create a single instance of any class. It can be used to instantiate Singletons from public classes with non-public constructors, and Singletons from non-public classes as well.

The main motivation for this solution is to have the Singleton pattern written in only one place, reusable by all classes that need to follow that pattern.

Simply use Singleton<T>.Instance to get a Singleton instance.


There are already very good articles (Lazy vs. Eager Init Singletons / Double-Check Lock Pattern and Implementing the Singleton Pattern in C#) that describe the challenges and caveats of developing a Singleton in .NET; I won't go into the details again. There are also some Singletons using Generics here and there (see Generic Singleton Provider as an example), but none were solving the problem of creating a single instance of a class with a non-accessible constructor (something that all Singletons should have).


Singleton<T> uses the Double-Check Lock Pattern rather than static type initialization. The motivation behind this choice is that error-recovery and retries after a type-initializer failure are impossible in .NET (once a type-initializer fails, trying to create a class instance will always throw an exception, even if the error was meanwhile resolved). The chosen implementation strategy provides more flexibility for better error recovery.

Singleton<T> also forces the target class constructor to be private or protected to prevent casual class instantiation.


This is the generic Singleton class:

public static class Singleton<T>
       where T : class
  static volatile T _instance;
  static object _lock = new object();

  static Singleton()

  public static T Instance
      if (_instance == null)
        lock (_lock)
          if (_instance == null)
            ConstructorInfo constructor = null;

              // Binding flags exclude public constructors.
              constructor = typeof(T).GetConstructor(BindingFlags.Instance | 
                            BindingFlags.NonPublic, null, new Type[0], null);
            catch (Exception exception)
              throw new SingletonException(exception);

            if (constructor == null || constructor.IsAssembly)
            // Also exclude internal constructors.
              throw new SingletonException(string.Format("A private or " + 
                    "protected constructor is missing for '{0}'.", typeof(T).Name));

            _instance = (T)constructor.Invoke(null);

      return _instance;

The type parameter T represents the class that must be instantiated like a Singleton.

Singleton<T> uses the class constraint to force the type parameter to be a reference type. The new() constraint, which forces the type parameter to have a public parameterless constructor, is not used here, because the goal of the generic class is to provide single instance creation for classes with non-public constructors.

_instance is defined using the volatile keyword, and a dummy object, _lock, is used to synchronize threads with the double-check lock pattern. See Lazy vs. Eager Init Singletons / Double-Check Lock Pattern for the details of this strategy.

Singleton<T> has a static constructor: it simply makes sure that static fields initialization occurs when the Instance property is called the first time and not before.

The initialization of the _instance field is made by Reflection using the type parameter. typeof(T) first gets the type of the type parameter, then GetConstructor gets its constructor, and Invoke finally returns the new instance. The BindingFlags tells GetConstructor to search the constructor in the non-public (BindingFlags.NonPublic) instance members (BindingFlags.Instance) of the type. The search doesn't include public members, and the last if statement excludes internal constructors, as it is a best practice to keep Singleton constructors private or protected (you don't want anybody else to instantiate these classes).

As you can presume, GetConstructor can throw an exception if the type parameter is not a class, as the class constraint also allows interface, delegate, or array types. There's just so much you can do with these constraints.

Using Singleton<T>

Another best practice of the Singleton pattern is to have every Singleton return its own single instance. This is usually done by a static property named Instance. The following code snippet shows how to use Singleton<T> in a property.

public static SingleInstanceClass Instance
    return Singleton<SingleInstanceClass>.Instance;


The demo shows the life cycle of the SingleInstanceClass singleton. The code is self-explanatory:

// SingleInstanceClass is a Singleton.

public class SingleInstanceClass
  // Private constructor to prevent
  // casual instantiation of this class.
  private SingleInstanceClass() 
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("SingleInstanceClass created.");

  // Gets the single instance of SingleInstanceClass.
  public static SingleInstanceClass Instance 
    get { return Singleton<SingleInstanceClass>.Instance; } 

  public static int Count { get { return _count; } }
  public static void DoStatic()
      { Console.WriteLine("DoStatic() called."); }
  public void DoInstance()
      { Console.WriteLine("DoInstance() called."); }

  // Instance counter.
  private static int _count = 0;

class Program
  static void Main()
    // Show that initially the count is 0; calls
    // a static property which doesn't create the Singleton.
    Console.WriteLine("Initial instance count: {0}", 

    // Similar to above; show explicitly that calling
    // a static methods doesn't create the Singleton.
    Console.WriteLine("Calling DoStatic()");
    Console.WriteLine("Instance count after DoStatic(): {0}", 

    // Show that getting the instance creates the Singleton.
    Console.WriteLine("Calling DoInstance()");
    Console.WriteLine("Instance count after first DoInstance(): {0}", 

    // Show that getting the instance
    // again doesn't re-instantiate the class.
    Console.WriteLine("Calling DoInstance()");
    Console.WriteLine("Instance count after second DoInstance(): {0}", 

The program output is:

Running the Singleton demo...


There are many ways to implement the Singleton pattern in C#. Singleton<T> uses Reflection to make it a write-once-for-all solution.


  • 2009-04-18: Refactored to use the double-check lock pattern and the volatile keyword rather than a type-initializer. Also added SingletonException.
  • 2009-06-07: Replaced typeof(T).InvokeMember with typeof(T).GetConstructor to support the Compact Framework.


This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


About the Author

Martin Lapierre
Web Developer
Canada Canada
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralRe: Not convinced Pin
Erich Ledesma21-Apr-09 4:45
memberErich Ledesma21-Apr-09 4:45 
GeneralRe: Not convinced Pin
Martin Lapierre21-Apr-09 5:57
memberMartin Lapierre21-Apr-09 5:57 
Questionpublic constructor? Pin
Sean Rhone20-May-08 7:53
memberSean Rhone20-May-08 7:53 
AnswerRe: public constructor? Pin
Martin Lapierre20-May-08 13:47
memberMartin Lapierre20-May-08 13:47 
QuestionThread Safety Pin
Jammer8-May-08 11:04
memberJammer8-May-08 11:04 
AnswerRe: Thread Safety Pin
Martin Lapierre8-May-08 14:49
memberMartin Lapierre8-May-08 14:49 
GeneralRe: Thread Safety Pin
Jammer9-May-08 1:34
memberJammer9-May-08 1:34 
GeneralReflection not required Pin
ilsandor18-May-07 2:52
memberilsandor18-May-07 2:52 
GeneralRe: Reflection not required Pin
Martin Lapierre18-May-07 4:14
memberMartin Lapierre18-May-07 4:14 
GeneralRe: Reflection not required Pin
dimzon12-May-09 7:23
memberdimzon12-May-09 7:23 
GeneralRe: Reflection not required Pin
Martin Lapierre14-May-09 7:07
memberMartin Lapierre14-May-09 7:07 
GeneralFxCop and readonly declaration Pin
PlunderBunny27-Jan-07 18:39
memberPlunderBunny27-Jan-07 18:39 
GeneralRe: FxCop and readonly declaration Pin
Martin Lapierre28-Jan-07 4:18
memberMartin Lapierre28-Jan-07 4:18 
GeneralWatch out for controls Pin
Chuck77721-Aug-06 12:57
memberChuck77721-Aug-06 12:57 
GeneralRe: Watch out for controls Pin
Martin Lapierre22-Aug-06 7:12
memberMartin Lapierre22-Aug-06 7:12 
GeneralRe: Watch out for controls Pin
Chuck77722-Aug-06 7:50
memberChuck77722-Aug-06 7:50 
GeneralRe: Watch out for controls Pin
darrellp23-Apr-09 2:29
memberdarrellp23-Apr-09 2:29 
QuestionRe: Watch out for controls [modified] Pin
psidata2-Mar-07 1:19
memberpsidata2-Mar-07 1:19 
AnswerRe: Watch out for controls Pin
pianorain3163-Apr-07 13:03
memberpianorain3163-Apr-07 13:03 
GeneralSingleton Pin
KiwiPiet7-May-06 14:32
memberKiwiPiet7-May-06 14:32 
GeneralRe: Singleton Pin
Brian Leach9-May-06 8:46
memberBrian Leach9-May-06 8:46 
GeneralNice article Pin
NinjaCross6-May-06 3:13
memberNinjaCross6-May-06 3:13 
GeneralRe: Nice article Pin
Martin Lapierre6-May-06 4:44
memberMartin Lapierre6-May-06 4:44 
GeneralSuperb Pin
Josh Smith5-May-06 17:49
memberJosh Smith5-May-06 17:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190214.1 | Last Updated 9 Jun 2009
Article Copyright 2006 by Martin Lapierre
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid