DEV Community

Cover image for C# - Lazy Initialization
Keyur Ramoliya
Keyur Ramoliya

Posted on

1

C# - Lazy Initialization

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.");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We use the Lazy<T> class to defer the initialization of an ExpensiveResource object until it's accessed through lazyResource.Value.
  • The ExpensiveResource object is only created when Value 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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay