Easy Lazy Loading in C#: Boost Performance and Reduce Resource Usage!

Greg James
DotnetDevelopers
Published in
4 min readMar 14, 2023

--

In C#, there are many scenarios where you may want to defer the creation of an object until it’s actually needed. This is where the Lazy<T> class comes in handy. Lazy<T> is a class in C# that allows you to create an object that is only instantiated when it's actually needed. In this article, we'll explore what Lazy<T> is, how it works, and when to use it in your code.

What is Lazy<T>?

Lazy<T> is a class in the System namespace that is used to create objects that are lazily initialized. When you create an instance of Lazy<T>, it doesn't immediately create the object that it represents. Instead, it waits until the first time that you access the object, and then creates it.

Here’s an example of creating a Lazy<T> object:

Lazy<MyObject> lazyObject = new Lazy<MyObject>();

In this example, we’ve created a Lazy<MyObject> object. Note that we haven't created an instance of MyObject yet. The Lazy<T> object will create an instance of MyObject the first time we access it.

How does Lazy<T> work?

When you create an instance of Lazy<T>, it creates a LazyThreadSafetyMode object that determines how the object will be accessed. The LazyThreadSafetyMode object…

--

--

Greg James
DotnetDevelopers

Let's get better together! Follow for tips and insights to help you grow in both your skills and confidence as a developer!