Skip to content

C# Feature - Null-coalescing assignment

The ??= operator assigns the right-hand value only if the left-hand variable, property, or indexer currently evaluates to null.

This feature was introduced in C# 8.0 (2019).

Before ??=, lazy initialization often required repeated variable names and a full if block. ??= makes the intent explicit: initialize only once, only if missing.

target ??= fallbackValue;
  • Use it for lazy initialization of collections, caches, settings objects, or dependency-created instances.
  • Use it when the fallback should only be created if the current value is missing.
  • Prefer it over verbose null-check blocks when the logic is just โ€œinitialize if null.โ€
if (cache == null)
{
cache = new Dictionary<string, string>();
}
cache ??= new Dictionary<string, string>();
private List<string>? _messages;
public void Add(string message)
{
(_messages ??= new List<string>()).Add(message);
}
  • Use ??= only when lazy initialization is the real goal, not as a substitute for broader validation logic.
  • The operator only checks for null; it does not handle empty strings, zero values, or empty collections.
  • Avoid hiding expensive object creation inside ??= unless that lazy creation is intentional.
  • C# 8 added ??= as the assignment form of null coalescing.