.NET Framework provides a System.Lazy<T> class that has all of the benefits of lazy initialization without the need to worry about synchronization overheads. Objects created using System.Lazy<T> are deferred until they are accessed for the first time. With the custom lazy code explained in previous sections, we can see that we moved the initialization part from the constructor to the method/property to support lazy initialization. With Lazy<T>, we don't need to modify any code.
There are multiple ways to implement lazy initialization patterns in C#. These include the following:
- Construction logic encapsulated inside a constructor
- Construction logic passed as a delegate to Lazy<T>
In the subsequent sections, we will try to understand these scenarios in depth.