.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#.


One thought on “.Net Framework 4.0: Using System.Lazy

Leave a Reply

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