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

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.