Monday, 13 October 2008

Singleton in C#

Once I've found a Singleton pattern implementation in C#

class Singleton<T> where T : new()
{
    private static readonly T inst = new T();
    public static T Instance
    {
        get { return inst; }
    }
}

I was suprised by the elegance of this code snippet (and also it is thread safe!)

This code could be used as follows:

internal class Singleton<T> where T : new()
{
    private static readonly T inst = new T();
    public static T Instance
    {
        get { return inst; }
    }
}

internal class Single
{
    public Single()
    {
        System.Console.WriteLine("Constructor!");
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        Single sss1 = Singleton<Single>.Instance;
        Single sss2 = Singleton<Single>.Instance;
    }
}

No comments: