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:
- When the creation of an object is expensive and we want to defer the creation until it is used.
- When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use the system memory or computing cycles to create it. By using the Lazy<Orders> to declare the Orders object for lazy initialization, you can avoid wasting the system resources when the object is not used.
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).