.NET 4 Baby Steps: Part V - Lazy
Note: This post is part of a series and you can find the rest of the parts in the series index.
Lazy
- you may need to create an object early but don't need it immediately.
- the creation is expensive (CPU, memory) or slow.
- you may not need the data the object provides when you create it.
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
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:
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.