How to perform lazy initialization in C#


Lazy initialization is a technique that defers the creation of an object until the first time it is needed. In other words, initialization of the object happens only on demand. Note that the terms lazy initialization and lazy instantiation mean the same thing—they can be used interchangeably. By taking advantage of lazy initialization, you can improve the application’s performance by avoiding unnecessary computation and memory consumption. In this article we’ll look at how we can perform lazy initialization in C#.

Let’s understand lazy loading with a simple example. Consider two classes, Customer and Order. The Customer class contains an Orders property that in turn references a collection of instances of the Order class. The Orders collection may contain a large amount of data and may even need a database connection to connect to the database and retrieve records. In such a case, there is no point in loading data in the Orders property until we need the data. Lazy initialization allows us to load the Orders collection only when the data is asked for.

Using the Lazy class in C#

Although you can write your own custom code to implement lazy initialization, Microsoft recommends using the Lazy class instead. The Lazy class in the System namespace in C# was introduced as part of .Net Framework 4.0 to provide a thread-safe way to implement lazy initialization. You can take advantage of this class to defer the initialization of resource-intensive objects in your application.

When you use the Lazy class, you need to specify the type of object you intend to create lazily in the type argument. Note that lazy initialization occurs when you access the Lazy.Value property. Here is an example of how the Lazy class can be used:

.) The following version of the StateManager class is thread-safe. At the same time, it demonstrates lazy initialization. Note that the explicit static constructor has been used to ensure that the C# compiler doesn’t mark the type as .