Skip to main content

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

Lazy<T> is a new class which has been added to cater for scenarios where

  • you may need to create an object early.
  • the creation is expensive (CPU, memory) or slow.
  • you may not need the data the object provides when you do the creation of the object.

An example of this is LINQ which does not actually execute the query when you define it. Execution of the LINQ query occurs only when you ask for the data or some calculation on the data (like .Count()). It is done this way to prevent slow or expensive (memory, CPU) operations from being called if they are not needed.

Lazy<T> allows you to assign an object, but not actually create it until needed. 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");
    }
}

Which produces a result of:

image

See how the start creation line is only after the assignment when we actually ask for the value. Methods on the object work the same, the first time you call a method it then does the creation.