Day 15 of 30-Day .NET Challenge: Lazy Initialization

Day 15 of 30-Day .NET Challenge: Lazy Initialization

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.

// 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:

// 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

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.

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
Contribute to ssukhpinder/30DayChallenge.Net development by creating an account on GitHub.github.com


C# Programming🚀

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

Follow us: Youtube | X | LinkedIn | Dev.to
Visit our other platforms: GitHub
More content at C# Programming

Did you find this article valuable?

Support C# Programming by becoming a sponsor. Any amount is appreciated!