C# Feature - Null-coalescing assignment
Null-coalescing assignment
Section titled โNull-coalescing assignmentโThe ??= operator assigns the right-hand value only if the left-hand variable, property, or indexer currently evaluates to null.
Introduced In
Section titled โIntroduced InโThis feature was introduced in C# 8.0 (2019).
Why This Feature Exists
Section titled โWhy This Feature Existsโ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;When To Use It
Section titled โWhen To Use Itโ- 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>();Practical Example
Section titled โPractical Exampleโprivate List<string>? _messages;
public void Add(string message){ (_messages ??= new List<string>()).Add(message);}Common Pitfalls
Section titled โCommon Pitfallsโ- 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.
Version Notes
Section titled โVersion Notesโ- C# 8 added
??=as the assignment form of null coalescing.