To unlock the full potential of your .Net Application, it’s essential to familiarize yourself with the Lazy<T> class.
To enhance the power of the .Net Application, make use of the Lazy<T> class to pause the instantiation of class until the object is needed.
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.
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.
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();
}
}
GitHub — ssukhpinder/30DayChallenge.Net *Contribute to ssukhpinder/30DayChallenge.Net development by creating an account on GitHub.*github.com
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
Also published here.