Being Lazy in C# 4

10/13/10

Being Lazy in C# 4

I’m playing with the new features of C#/.NET 4.0; this is some code I wrote in LINQPad to try out the System.Lazy<T> class.

void Main()
{
    Console.WriteLine("Running...");
    Expensive one = GimmeOne;
    Expensive two = GimmeOne;
    
    if (one == two) Console.WriteLine("Same instance");
}

private static readonly Lazy<Expensive> _lazy =
  new Lazy<Expensive>();
// If constructor arguments, use:
// new Lazy<Expensive>(() => new Expensive(args));

Expensive GimmeOne
{
    get
    {
        return _lazy.Value;  // thread safe
    }
}

class Expensive
{
    public Expensive()
    {
        Console.WriteLine("Creating expensive instance");
    }
}

Output:

Running...
Creating expensive instance
Same instance

Update - October 14, 2010

The private field does not have to be static; there’s seldom a need for a true Singleton.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.