Thursday, June 3, 2010

What is System.Lazy<T>

there is a new class in .Net framework 4.0 Called Lazy<T> that provides lazy initialization. Lazy initialization occurs the first time the Lazy<T>.Value property is accessed or the Lazy<T>.ToString method is called and the return value will be cached, it means the second time you access its value, the expression or function does not get executed.

lets take a look at an example.

public class ProductFactory
public static Product GetProduct()
return new Product{ProductID = 1, ProductName = "book"};

Then we can create a Lazy object;

var lazyProduct = new Lazy<Product>( () => {return ProductFactory.GetProduct();});

the parameter for Lazy<T> constructor is Func<T> (function that has no input parameter and returns T)

the GetProduct() method does not get executed unless we access the Value property.

var product = lazyProduct.Value;

next time if we access the Value property again, the GetProduct() method does not get executed and the cached return value will be returned.

There is a nice article about Lazy Computation in C#

kick it on



Post a Comment