Day 15 of 30-Day .NET Challenge: Lazy Initialization
Tags: dotnet, programming, csharp, aspnet
Published: 2024-04-03 04:52:36

To unlock the full potential of your .Net Application, it’s essential to familiarize yourself with the Lazy<T> class.


## Introduction

To enhance the power of the .Net Application, make use of Lazy<T> class to pause the instantiation of class until the object is needed.

### Learning Objectives

* A common mistake of developers

* How to use Lazy<T> class

### Prerequisites for Developers

* A basic understanding of C# language.

## Getting Started

### Developers common mistake

Developers often make  objects instantiated as soon as the application starts or when a class is instantiated, regardless of whether they are immediately needed or not.
```csharp
    // Initializing expensive resources upfront
    private readonly ExpensiveObject _expensiveObject = new ExpensiveObject();
    public ExpensiveObject ExpensiveObject => _expensiveObject;
```
The _expensiveObject can lead to wasted resources and reduced performance, especially if the ExpensiveObject is not used immediately or ever during the application's lifecycle.

### Efficient Method

The syntax for utilizing Lazy<T> is as follows:
```csharp
    // Using Lazy<T> to initialize resources only when needed
    private readonly Lazy<ExpensiveObject> _expensiveObject = new Lazy<ExpensiveObject>();
    public ExpensiveObject ExpensiveObject => _expensiveObject.Value;
```
The approach shifted to instantiate an object only when it needed. The .Net makes it easier to implement using Lazy<T> syntax and also safe.

## Complete Example

First, let’s define an ExpensiveResource class that simulates a delay
```csharp
    using System;
    using System.Threading;
    
    class ExpensiveResource
    {
        public ExpensiveResource()
        {
            Console.WriteLine("Initializing expensive resource... This might take a while.");
            // Simulating expensive initialization with a delay
            Thread.Sleep(2000); // Delay for 2 seconds
            Console.WriteLine("Expensive resource initialized!");
        }
    
        public void UseResource()
        {
            Console.WriteLine("Using the expensive resource.");
        }
    }
```
Now, let’s create the main part of the application, where Lazy<T> is used to initialize the ExpensiveResource lazily.
```csharp
    using System;
    
    class Program
    {
        private static Lazy<ExpensiveResource> _lazyExpensiveResource = new Lazy<ExpensiveResource>();
    
        static void Main(string[] args)
        {
            Console.WriteLine("Application started.");
            Console.WriteLine("Press any key to use the expensive resource...");
            Console.ReadKey();
    
            // Accessing the Value property of _lazyExpensiveResource for the first time triggers the initialization.
            _lazyExpensiveResource.Value.UseResource();
    
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
```
## Benefits of Using Lazy<T>

* Improved Performance

* Thread Safety

## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)