Lazy class in .NET 4

The concept of lazy is simple: sometimes creating a new instance of a class could be time-consuming, and you don't always need the full initialization of the class, but only a few members of it. So here we have the conpect of lazy construction: create or object, but complete the initialization only when all the fields are needed.

In previous versions of the .NET framework you had to implement this pattern by hand, but the .NET 4 introduces the Lazy class. The concept to build a lazy instances are simple:

  • define a private property containing the real value of the property you want to save (and don't initialize it), let's suppose you call it MyPropertyPrivate;
  • define your internal Lazy<T> property (let's say: call it MyPropertyLazy);
  • initialize the previous MyPropertyLazy as new Lazy<T>(() => { give a value to MyPropertyPrivate });
  • define a public property of type T, let's say called MyProperty, with a get accessor returning MyPropertyLazy.Value.

So in the end what happens is:

  1. a user access the public property MyProperty;
  2. MyProperty returns its value from MyPropertyLazy.Value;
  3. once "touched", MyProperty.Value evaluates the lambda expression,
  4. that finally executes and gives a value to MyPropertyPrivate.