08 Feb 2024
Intermediate
Lazy loading in C# .NET Core is a programming technique where objects or resources are loaded only when they are needed or accessed , rather than loading them all upfront. This helps improve performance and resource utilization by deferring initialization until necessary.
In C# .NET Core, you can achieve lazy loading using the Lazy<T>
class provided by the .NET framework. Here's a basic overview of how to achieve lazy loading using Lazy<T>
:
- Define the object or resource you want to lazily load.
- Instantiate a
Lazy<T>
object, specifying the type of the object/resource you want to load. - Access the
Value
property of theLazy<T>
object when you need to use the object/resource. This will trigger the lazy initialization if it hasn't been done already.
Here's a simple example demonstrating lazy loading using Lazy<T>
:
using System;
class Program
{
static void Main(string[] args)
{
// Instantiate a Lazy<T> object for lazy loading of an integer
Lazy<int> lazyInteger = new Lazy<int>(() =>
{
Console.WriteLine("Initializing lazy integer...");
return 42; // Some expensive operation to initialize the integer
});
// Access the Value property to trigger lazy loading
int value = lazyInteger.Value;
Console.WriteLine("Lazy integer value: " + value);
// Lazy loading occurs only once, subsequent accesses use the cached value
int cachedValue = lazyInteger.Value;
Console.WriteLine("Cached lazy integer value: " + cachedValue);
}
}
In this example:
- We create a
Lazy<int>
object namedlazyInteger
that will lazily load an integer value when accessed. - We provide a lambda expression to the
Lazy<int>
constructor, specifying the operation to initialize the integer value. - When we access the
Value
property oflazyInteger
, it triggers the lazy initialization and executes the provided lambda expression. - Subsequent accesses to the
Value
property use the cached value, avoiding the expensive initialization operation again.
You can apply this same principle to lazily load other types of objects or resources in your C# .NET Core applications as needed.