Lazy initialization is a design pattern that defers the creation or calculation of an object until it's actually needed. This can be particularly useful for resource-intensive objects requiring expensive setups.
Here's an example using the Lazy<T>
class:
using System;
public class Program
{
public static void Main()
{
// Create a Lazy<T> object for deferred initialization
Lazy<ExpensiveResource> lazyResource = new Lazy<ExpensiveResource>(() => new ExpensiveResource());
// Access the resource when needed
ExpensiveResource resource = lazyResource.Value;
// Use the resource
resource.DoSomething();
}
}
public class ExpensiveResource
{
public ExpensiveResource()
{
// Simulate expensive initialization
Console.WriteLine("ExpensiveResource is being initialized.");
}
public void DoSomething()
{
Console.WriteLine("ExpensiveResource is doing something.");
}
}
In this example:
- We use the
Lazy<T>
class to defer the initialization of anExpensiveResource
object until it's accessed throughlazyResource.Value
. - The
ExpensiveResource
object is only created whenValue
is called and is cached for subsequent access. - This allows you to avoid the cost of initializing the resource until it's actually needed.
Lazy initialization is beneficial when you want to improve your application's performance and memory usage by postponing the creation of expensive objects until they are required. It's commonly used in scenarios like database connections, file loading, or complex object creation.
Top comments (0)