.NET 4 Baby Steps: Part V - Lazy

12122009025 Note: This post is part of a series and you can find the rest of the parts in the series index.

Lazy is a new class that has been added to handle scenarios where:

An example of this is LINQ, which does not actually execute the query when you define it. Execution occurs only when you access the data or perform calculations on it (like .Count()). This design prevents slow or expensive (memory, CPU) operations from running if they’re unnecessary.

Lazy allows you to assign an object without creating it until needed. Here’s an example of usage:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Before assignment");
        Lazy<Slow> slow = new Lazy<Slow>();
        Console.WriteLine("After assignment");

        Thread.Sleep(1000);
        Console.WriteLine(slow);
        Console.WriteLine(slow.Value);
    }
}

class Slow
{
    public Slow()
    {
        Console.WriteLine("Start creation");
        Thread.Sleep(1000);
        Console.WriteLine("End creation");
    }
}

The output shows that the creation starts only when the value is accessed:

image

Notice that the "Start creation" message appears only after assignment when you first request the value. The same behavior applies to methods: the object is created only on the first method call.