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?

 |