Total Downloads

2,593,416

Total Files

9,206

Latest Update

10

How to perform lazy initialization in C#

Posted September 25, 2017 | Windows


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<T> class in C#

Although you can write your own custom code to implement lazy initialization, Microsoft recommends using the Lazy<T> class instead. The Lazy<T> 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<T> 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<T>.Value property. Here is an example of how the Lazy<T> class can be used:



Source link

')
ankara escort çankaya escort çankaya escort escort bayan çankaya istanbul rus escort eryaman escort ankara escort kızılay escort istanbul escort ankara escort ankara escort escort ankara istanbul rus Escort atasehir Escort beylikduzu Escort Ankara Escort malatya Escort kuşadası Escort gaziantep Escort izmir Escort