Friday 18 January 2013

Singleton in .NET 4.0 or Above

Below is an example of a class that is implementing Singleton pattern in .NET 4.0 or above. The framework added a new type called System.Lazy<T> that makes laziness (lazy construction) really simple and also thread-safe as well. Prior to this we had to use static constructor, double-check locking or other tricks to ensure the laziness and thread-safe.
public sealed class Singleton
{
    private static readonly Lazy<Singleton> _instance =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return _instance.Value; } }

    private Singleton()
    {
        //Console.Write("... Singleton is created ...");
    }
}

We could also use a generic template like this:
public static class Singleton<T> where T : new()
{
    private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
        
    public static T Instance { get { return _instance.Value; } }
} 
and the class type to be passed:
public class Car
{
    public Car()
    {
        Console.WriteLine("Car is created");
    }
}

References and further reading:
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx
http://csharpindepth.com/articles/general/singleton.aspx

No comments: