Click here to Skip to main content
11,928,352 members (46,955 online)
Click here to Skip to main content
Add your own
alternative version


20 bookmarked

Generic Singleton Design Pattern

, 31 Aug 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Generic Singleton Design Pattern C#


The article describe Generic Singleton Design Pattern, that base on  static constractor behavior.


There are two types of class constructors in C# 'regular constructor' with or without arguments and 'static constructor' without arguments.

Regular Constructor
1. In case the class doesn't write with any constructor, C# provides an implicit default constructor, a constructor with no argument.
2. Constructors can be overloaded
3. Constructors are called in the order of inheritance

Static Constructor
1. A static constructor is thread-safe
2. A static constructor for a class executes at most once in a given application domain
3. An execution of the static field initializers occurs immediately prior to executing that static constructor
4. A static constructors are called in the reverse order of inheritance

Generic Singleton

The Generic Singleton Design Pattern is base principle that "a static constructors are called in the reverse order of inheritance" and "A static constructor for a class executes at most once".

/// <summary>
/// Singleton Template, OOD
/// </summary>
/// <typeparam name="T">class name</typeparam>
/// <example>
/// <code>
/// class MySingleton:Singleton<MySingleton>{}
/// </code>
/// </example>
public class Singleton<T> where T : class
         #region Ctor
         protected Singleton(){}
	#region Static Ctor
	static Singleton()
                  Type derivedClassType = typeof(T);
                    if (IsConstructorCodeInvalid)
                       throw new SingletonException(string.Format("The Singleton class name:{0} should have only private C'tor.", derivedClassType.Name));

		  ConstructorInfo ctorInfo = typeof(T).GetConstructor(
                                     BindingFlags.Instance | 
                                     BindingFlags.NonPublic |
				null, CallingConventions.HasThis,
				Type.EmptyTypes, null);

                    _Instance = (T)ctorInfo.Invoke(null);
                  catch (SingletonException){
		catch (Exception ex){
                     string err = string.Format(
			"Fail to create : {0} . \n Error Message : {1} \n StackTrace: {2}",
			 ex.InnerException != null ? ex.InnerException.Message : ex.Message,
		  throw new SingletonException(err);

	#region Static public
	static public T Instance { get { return _Instance; } }

         #region Private Static Methods
         static private bool IsConstructorCodeInvalid
                foreach (ConstructorInfo ctorInfo in typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
                    if (!ctorInfo.IsPrivate)
                        return true;
                return false;

	#region Private Members
	static private T _Instance;

Error Handling

 In case of error the SingletonException object is throw, there are several cases:

  • There is public, internal or protected c'tor.
  • The private c'tor not exist.
  • Problem while initialize derived  class.
public class SingletonException : ApplicationException
	internal SingletonException(string err)
		: base("Exception while trying to create Singleton.\n " + err) { }


Using the code

The singleton design pattern is mean single instance of class therefore the c'tor of the derived class, MySingleton, mast be private.

public class MySingleton:Singleton<MySingleton>
 #region Private Ctor
 private MySingleton(){}

 public string Name {get{return "MySingleton";}}


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

tomer bracksmayer
Program Manager
Israel Israel
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
mwdiablo2-Sep-09 0:06
membermwdiablo2-Sep-09 0:06 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 31 Aug 2009
Article Copyright 2009 by tomer bracksmayer
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid