With lazy initialization, the memory for an object is not allocated until it is needed. It is used, mainly, to improve the performance and it also reduces the unnecessary computations and memory requirements. This may prove to be useful in the following scenarios:

Example



We can declare and use this by creating a lambda expression to pass in our string parameter:



We then have access to the IsValueCreated property, which tells us whether or not the instance has been created along with telling us about the Value property, which will construct and return our actual instance on demand.

Here’s an example showing a complete program using the MyClass above, demonstrating the usage of Lazy<T>:



The above program, when run, prints out



So, this LAZY type automatically delayed our construction until the first type accessed it (instance2.Value.MyData).