.NET 4.0 is so Lazy

With .NET 4.0 there is a new class added to the System namespace called Lazy<T>. This class is what the name says, lazy. Here is an example where Lazy is used:

var lazy = new Lazy<IList<OrderRow>>(
                                () =>
                                        var rows = //get order rows;
                                        return rows;

var rows = lazy.Value;

The Lazy<T>’s constructor can take a Func<T> as an argument, the function passed as an argument to the contractor will first be invoked when the Value property of the Lazy<T> class is used, but not invoked the next time the Value property is used. The code above will first execute the function passed as an argument when the we request the value of the Lazy<T>, the returned value of the function will be cached. The next time Value is used, the function will not be invoked, instead the cached value will be returned. This class  can for example be used when we want some kind of Lazy Loading.

I’m on twitter: http://www.twitter.com/fredrikn


Comments have been disabled for this content.