navigation
 Saturday, January 26, 2008

I don't know how many times I have implemented the Singleton Design Pattern in C#, but it was starting to get old...

So I Googled the net, looking for something I could re-use. I found this excellent article, and adapted it to use Generics. This is what I came up with:

using System;

namespace TT
{
    #region Singleton<T>
    /// <summary>
    /// Provides a Singleton implementation using Generics.
    /// </summary>
    /// <typeparam name="T">Type of singleton instance</typeparam>
    public sealed class Singleton<T> where T : new() {
        Singleton() {}

        public static T Instance {
            get {
                return Nested.instance;
            }
        }

        class Nested {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested() {}

            internal static readonly T instance = new T();
        }
    }
    #endregion
}

You can easily use this class to create a Singleton for any type you want, all it has to do is have a default parameterless constructor. For instance:

Singleton<StoryBoardManager>.Instance.Stop();

Pretty neat, huh?

 | 
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, i, strike, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview