Creating expensive objects at startup wastes resources if they’re never used. Lazy
Without Lazy:
public class ReportService
{
// Created on class instantiation even if never used
private readonly PdfGenerator _pdfGen = new PdfGenerator(); // Heavy!
private readonly ExcelExporter _excelExporter = new ExcelExporter(); // Heavy!
public void GeneratePdf() => _pdfGen.Generate();
}
With Lazy
public class ReportService
{
// Created only when first accessed
private readonly Lazy _pdfGen = new(() => new PdfGenerator());
private readonly Lazy _excel = new(() => new ExcelExporter());
public void GeneratePdf() => _pdfGen.Value.Generate(); // Initialized here
public void ExportExcel() => _excel.Value.Export(); // Initialized here
}
// If only PDF is used, ExcelExporter is never created!
Thread-Safe:
// Thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication) var lazy = new Lazy(() => new ExpensiveObject(), true); // Multiple threads access .Value → only one creates the object
Check if Created:
if (_pdfGen.IsValueCreated)
Console.WriteLine("PDF Generator was used");
