The Generic Lazy Type

Lazy<T> is a monad type that was introduced in .NET 4 and provides an alternative mechanism for implementing lazy initialization. Lazy initialization is where you intentionally delay the creation of an object that is expensive to create.
 
You would typically want to use lazy initialization in scenarios where the object (which is expensive to create) may or may not be used in the execution flow of your program. In this case, it makes sense to only initialize the object if it is required. One reliable place where you may have seen the lazy initialization tactic being used is in an implementation of a singleton class – which will have a method or property that returns the singleton instance, for example,
  1. public MySingletonClass GetInstance()  
  2. {  
  3.     if (_singleton == null)  
  4.         _singleton = new MySingletonClass();  
  5.   
  6.     return _singleton;  
  7. }  
The logic before the return statement is an example of lazy initialization, where the singleton is only instantiated the first time GetInstance is called and never before it. Subsequent calls to GetInstance will then also return the same instance, hence we have an implementation of the singleton design pattern. In this particular case, we don’t know if MySingletonClass is expensive to create, and we don’t particularly care as we’re using lazy initialization to prevent multiple instances of MySingletonClass from being created.
 
If we now go back to the mainstream use for lazy initialization, where we want to delay instantiation of expensive-to-create objects, you could adapt the pattern above where you conditionally instantiate an instance of an object. However, since .NET 4, you have an alternative option with the use of Lazy<T>. An instance of Lazy<T> wraps around your expensive-to-create object, you pass this instance around in your code and whenever the underlying expensive-to-create object is required, you can call the Value property on Lazy<T> which will instantiate the object and return it to you.
 
The following contrived example should make it more clear. Imagine you have a Customer class and an Order class. A single customer can have many orders, so we’ll make use of composition and have the Customer class support a List of Order objects. The Customer class has one constructor that accepts a customer ID. Using the supplied ID, the constructor then goes and retrieves the orders for the customer from an order repository. Note that in reality your entity classes will usually be dumb and just support getter and setter properties and it’ll be the responsibility of your data access layer/framework (like Entity Framework) to instantiate and populate your entities appropriately. Continuing with our contrived example, our initial attempt may, therefore, look like,
  1. public class Order { }  
  2.   
  3. public class Customer  
  4. {  
  5.     public int Id { getprivate set; }  
  6.     public string Name { getset; }  
  7.     public List<Order> Orders { getset; }  
  8.   
  9.     public Customer(int id)  
  10.     {  
  11.         Id = id;  
  12.         Name = "Ms Foo Bar";  
  13.   
  14.         // Simulate getting lots of orders from an  
  15.         // order repository  
  16.         Orders = Enumerable  
  17.             .Repeat<Order>(new Order(), 200)  
  18.                 .ToList();  
  19.     }  
  20.   
  21.     public override string ToString()  
  22.     {  
  23.         return string.Format(  
  24.             "I'm customer with id {0}", Id);  
  25.     }  
  26. }  
As the code indicates, it would be expensive to instantiate a Customer object if we didn’t require the order information contained within it. This is where you would apply the concept of lazy initialization. In this case, we’ll make use of the Lazy<T> type. The following code shows how the Customer class would look if we lazily instantiate the Orders list using Lazy<T>.
  1. public class Customer  
  2. {  
  3.     public int Id { getprivate set; }  
  4.     public string Name { getset; }  
  5.     public Lazy<List<Order>> Orders { getset; }  
  6.   
  7.     public Customer(int id)  
  8.     {  
  9.         Id = id;  
  10.         Name = "Ms Foo Bar";  
  11.   
  12.         Orders = new Lazy<List<Order>>(() => {  
  13.             // Simulate getting lots of orders from an   
  14.             // order repository   
  15.             return Enumerable  
  16.                 .Repeat<Order>(new Order(), 200)  
  17.                     .ToList();  
  18.             }  
  19.         );  
  20.   
  21.         Debug.WriteLine(this);  
  22.     }  
  23.   
  24.     public override string ToString()  
  25.     {  
  26.         return string.Format(  
  27.             "I'm customer with id {0}", Id);  
  28.     }  
  29. }  
As you can see, the constructor of the Customer class instantiates an instance of Lazy<T> that wraps around the List of Order objects. The constructor of Lazy<T> is passed a lambda expression that expresses what needs to be returned when the list of orders is requested for (our expensive logic). Notice I’ve also put a call to Debug.WriteLine so you can observe the output of the following code and see how this behaves.
 
 var customer = new Customer(1);
  1.                          
  2. Debug.WriteLine("Are orders instantiated? {0}",   
  3.     customer.Orders.IsValueCreated);  
  4.   
  5. // Ok, we now want the orders...  
  6. var ordersForCustomer = customer.Orders.Value;  
  7.   
  8. Debug.WriteLine("Are orders instantiated? {0}",   
  9.     customer.Orders.IsValueCreated);  
  10.   
  11. Debug.WriteLine("Customer {0} has {1} order(s)",   
  12.     customer.Id, ordersForCustomer.Count);  
If you execute the code above using the updated Customer class, you’ll find that instantiating a Customer object is no longer an expensive operation. The output you should see in your debug window is,
 
I'm customer with id 1
Are orders instantiated? F
alse Are orders instantiated?
True Customer 1 has 200 order(s) 
 
Notice that when the Customer object was initialized, the runtime executed the constructor logic as expected (verifiable with the ToString output). We then check our Lazy objects IsValueCreated property to ensure it hasn’t yet created an instance of the list and populated it. The property returned False as expected. On the next line, we explicitly call the Value property on the Orders property (our Lazy object) – this forces our lazy object to instantiate.
 
We re-query the IsValueCreated property which now returns True and finally, we output the order count to show that the orders have been successfully lazily-loaded.