Skip to content

C# Feature ๏ฟฝ Lazy properties

Lazy properties defer work until a value is first requested. Implement with a private backing field and the null-coalescing assignment operator (??=).

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.