It’s Worth To Be Lazy<>

By | February 19, 2013

In the past few projects I saw a lot of wrong implemented Singleton patterns. Since Microsoft released the class “Lazy<>” in .NET 4.0, Singleton is much easier to implement. So… be lazy and use the class Lazy<> 😉

Here is an example:
This code here initializes the “_instance” variable when accessing the the “Instance” property for the first time.
Lazy<> ensures thread-safe lazy initialization.

public class Unique
{
    private static readonly Lazy<Unique> _instance = new Lazy<Unique>(() => new Unique());

    private Unique() { }

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

And here are two examples without the Lazy<> type.

Eager initialization

public class ExampleOne
{
    private static readonly ExampleOne _instance = new ExampleOne();

    private ExampleOne() { }

    public static ExampleOne Instance
    {
        get { return _instance; }
    }
}

Lazy initialization

public class ExampleTwo
{
    private static readonly object _sync = new object();
    private static volatile ExampleTwo _instance;

    private ExampleTwo() { }

    public static ExampleTwo Instance
    {
        get 
        {
            if (_instance == null)
            {
                lock (_sync)
                {
                    if (_instance == null)
                    {
                        _instance = new ExampleTwo();
                    }
                }
            }
            return _instance;
        }
    }
}