O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Lazy Initialization Using Lazy<T>

Introduced in .NET 4.0, the generic Lazy<T> class allows delayed initialization of some data that might not be required during a program’s lifetime. If that’s the case, it would be wasteful to precompute such a value in all circumstances.

The Lazy<T> class can be used in a number of ways, all of which require you to tell it how to create a new instance of type T. One is by giving it a Func<T> delegate that acts as the instance factory:

private Lazy<double> _pi = new Lazy<double>(() => {                               return /* long running computation of PI */;                           });

If you must obtain the value of the expensive computation, a simple call to the get-only

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required