.Net Framework 4.0: Using System.Lazy<T>

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

C#
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();
}

VB.NET


Private Shared Sub Main(ByVal args As String())
    Dim lazyString = New Lazy(Of String)(Function() Do
        ' Here you can do some complex processing
        ' and then return a value.
        Console.Write("Inside lazy loader")
        Return "Lazy loading!"
    End Function)
    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()
End Sub

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


kick it on DotNetKicks.com pimp it Progg it Shout it

2 Comments

  • 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?

  • @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.

Comments have been disabled for this content.