.Net Framework 4.0: Using System.Lazy

.Net Framework 4.0 provides us with a new class called Lazy<T>. As documentation sais then Lazy<T> provides support for several common patterns of lazy initialization, including the ability to initialize value types and to use null values. So it is construct that helps us implement lazy loading.

I wrote a little code example on Visual Studio 2010 that illustrates how to use Lazy<T>.

static void Main(string[] args)
{
   
var lazyString = new Lazy<string
>(
        () =>
        {
           
// Here you can do some complex processing
            // and then return a value.
            Console.Write("Inside lazy loader"
);
           
return "Lazy loading!"
;
        });
   
Console.Write("Is value created: "
);
   
Console
.WriteLine(lazyString.IsValueCreated);

   
Console.Write("Value: "
);
   
Console
.WriteLine(lazyString.Value);

   
Console.Write("Value again: "
);
   
Console
.WriteLine(lazyString.Value);

   
Console.Write("Is value created: "
);
   
Console
.WriteLine(lazyString.IsValueCreated);

   
Console.WriteLine("Press any key to continue ..."
);
   
Console.ReadLine();
}

When we run this code we will get the following output.

    Is value created: False
Inside lazy loader Value: Lazy loading!
Value again: Lazy loading! Is value created: True Press any key to continue …

The value of our Lazy<string> will be initialized when we first ask it and then it will be stored for subsequent calls. Notice that there is one Console.WriteLine inside lazy initialization function and if you look at output you can see that this function is run only once. So only thing you have to do is to write initialization function and Lazy<T> makes all the work automatically.

I found also one example that may give you better explanations about internals of Lazy<T>:Lazy Computation in C#.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    3 thoughts on “.Net Framework 4.0: Using System.Lazy

    • February 23, 2011 at 5:17 pm
      Permalink

      I do not think I like this new feature. Lazy loading should be an intrinsic feature of a property. IE, the user of your API should not have to call “.value” or even know that the propery is returning a generic lazy type. Why couldn’t they have implemented this as a language (keyword) feature instead of a CLR type which could be handled by the compiler instead?

    • August 30, 2011 at 10:09 am
      Permalink

      @Jeremy Rabalais – You make an interesting point, but there’s nothing to stop you using this implementation without compromising your API, such as by putting a property accessor around access to the lazy value. I think using System.Lazy in this manner in the internal implementation makes the intent of the code very clear, and reduces the opportunity to introduce poor lazy loading implementation or DRY violations.

    • Pingback:Using Lazy and abstract wrapper class to lazy-load complex system parameters | Gunnar Peipman - Programming Blog

    Leave a Reply

    Your email address will not be published. Required fields are marked *