C# Concept - Lazy properties
Overview
Section titled βOverviewβLazy properties are a property design pattern, not a dedicated C# release feature. The pattern is usually implemented with ordinary properties plus deferred initialization.
Introduced In
Section titled βIntroduced InβThis pattern has been possible since C# 1.0 (2002). The ??= operator used in many modern examples was introduced in C# 8.0 (2019).
Example
Section titled βExampleβpublic class Person{ private string? _name; public string Name => _name ??= LoadName();
private string LoadName() => "Lazy Loaded Name";}- Use
Lazy<T>or locking when multiple threads can initialize the value. - Reset the backing field when the cached value must be recomputed.