C# Feature ๏ฟฝ Lazy properties
Overview
Section titled โOverviewโLazy properties defer work until a value is first requested. Implement with a private backing field and the null-coalescing assignment operator (??=
).
Example
Section titled โExampleโpublic class Person{ private string? _name; public string Name => _name ??= LoadName();
private string LoadName() { // Simulate an expensive operation (I/O, computation, etc.) return "Lazy Loaded Name"; }}
- Thread-safety: wrap initialization in
Lazy<T>
or a lock if multiple threads may read the property. - Persistence: cache invalidation can be modeled by resetting the backing field to
null
.