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

Sukhpinder Singh - Apr 3 - - Dev Community

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

Introduction

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

Learning Objectives

  • A common mistake of developers

  • How to use Lazy 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;
Enter fullscreen mode Exit fullscreen mode

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 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;
Enter fullscreen mode Exit fullscreen mode

The approach shifted to instantiate an object only when it needed. The .Net makes it easier to implement using Lazy 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.");
        }
    }
Enter fullscreen mode Exit fullscreen mode

Now, let’s create the main part of the application, where Lazy 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();
        }
    }
Enter fullscreen mode Exit fullscreen mode

Benefits of Using Lazy

  • Improved Performance

  • Thread Safety

Complete Code on GitHub

GitHub — ssukhpinder/30DayChallenge.Net

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .