Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

.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

Comments

progg.ru said:

Thank you for submitting this cool story - Trackback from progg.ru

# May 20, 2009 1:59 AM

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# May 21, 2009 8:39 AM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# May 21, 2009 8:42 AM

DotNetBurner - .net Framework said:

DotNetBurner - burning hot .net content

# May 21, 2009 8:43 AM

PimpThisBlog.com said:

Thank you for submitting this cool story - Trackback from PimpThisBlog.com

# May 21, 2009 8:45 AM

gOODiDEA.NET said:

.NET What's New in the BCL in .NET 4 Beta 1 How CLR maps SEH exceptions to managed exception types Announcing

# May 23, 2009 9:05 PM

gOODiDEA said:

.NETWhat'sNewintheBCLin.NET4Beta1HowCLRmapsSEHexceptionstomanagedexception...

# May 23, 2009 9:08 PM

Community Blogs said:

.NET What&#39;s New in the BCL in .NET 4 Beta 1 How CLR maps SEH exceptions to managed exception types

# May 23, 2009 9:45 PM

Code Monkey Labs said:

Pick of the week: IP and Non-Competes for Employees General Visual Studio 2010 Beta 1 : Go get the first beta of the next version of Visual Studio! Microsoft Set To Announce Commercial Availability of Windows Azure at PDC This Year : Alin Irimie has some

# May 26, 2009 11:25 AM

Gunnar Peipman's ASP.NET blog said:

Here are my postings about Visual Studio 2010 and .Net Framework 4.0 that may be interesting to my readers

# May 27, 2009 3:48 AM

Level Up said:

.NET 4.0 New Feature - Generic Lazy class

# November 7, 2010 10:39 AM

Jeremy Rabalais said:

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?

# February 23, 2011 12:17 PM

Lazy « prabhudotnet said:

Pingback from  Lazy &laquo; prabhudotnet

# May 17, 2011 7:57 AM

James World said:

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

# August 30, 2011 6:09 AM

Gunnar Peipman's ASP.NET blog said:

.NET Framework 4.0 introduced new class called Lazy&lt;T&gt; and I wrote blog post about it: .Net Framework

# November 11, 2011 7:19 AM