C# Null Coalescing Assignment Operator
c# null coalescing assignment operator: Learn how to use the C# null coalescing assignment operator (??=) to assign values only when a variable is null, with practical...
The Null Coalescing Assignment Operator in C#
The C# null coalescing assignment operator ??= assigns the right-hand operand to the left-hand operand only when the left-hand operand is null. It was introduced in C# 8.0 and works with reference types and nullable value types. The operator is a shorthand for the common pattern of checking for null before assigning a fallback value.
string message = null; message ??= "Hello, world"; Console.WriteLine(message); // "Hello, world"
In this example, message is null, so the assignment occurs. If message already had a non-null value, the assignment would be skipped and the right-hand operand would not be evaluated.
Syntax and Evaluation Rules
The left operand of ??= must be a variable, property, or indexer element. The right operand is evaluated only when the left operand is null. This short-circuit behavior matters when the right side has side effects or is expensive to compute.
List<int> numbers = null; numbers ??= new List<int>(); numbers.Add(1);
Here, the list is created only if it was null. If numbers already referenced a list, the new List<int>() expression is never evaluated.
The operator works with nullable value types as well:
int? count = null; count ??= 0; Console.WriteLine(count.Value); // 0
Comparison with Alternative Approaches
Before C# 8.0, the same behavior required an explicit if statement or the null coalescing operator ?? combined with assignment:
if (name == null) { name = "default"; }
or
name = name ?? "default";
The ??= operator is more concise and makes the intent clearer: assign a fallback only when the current value is null. Unlike ??, which always evaluates the right side and assigns the result, ??= only evaluates the right side when needed.
| Approach | Code | Right side evaluated? |
|---|---|---|
if statement | if (x == null) x = y; | Only if x is null |
?? operator | x = x ?? y; | Always |
??= operator | x ??= y; | Only if x is null |
The ?? operator is still useful when you need to assign a value to a different target or when the left side is not a variable.
Practical Use Cases
The operator is commonly used for lazy initialization of fields or properties. Consider a class that loads a configuration only once:
private List<string> _items; public List<string> Items { get { _items ??= LoadItems(); return _items; } }
This ensures LoadItems() is called only once, on first access.
Another common scenario is updating a dictionary with a default value:
var lookup = new Dictionary<string, List<int>>(); string key = "example"; lookup[key] ??= new List<int>(); lookup[key].Add(42);
Without ??=, you would need to check ContainsKey or use TryGetValue to avoid overwriting an existing list.
Common Mistakes and Pitfalls
One mistake is using ??= with a non-nullable value type. The compiler will warn because a non-nullable value type can never be null, making the operator pointless.
Another pitfall is assuming the right side is always evaluated. Because the operator short-circuits, any side effects in the right operand are skipped when the left operand is non-null. This can be surprising if the right side increments a counter or writes to a log.
The operator also cannot be used with null on the left side directly, because the left operand must be assignable. For example, null ??= value is invalid.
Performance and Allocation Considerations
The main performance benefit of ??= is that it avoids evaluating the right operand when it is not needed. If the right side allocates a new object, this can reduce unnecessary allocations in code paths where the left value is frequently non-null.
For example, in a property getter that uses lazy initialization, ??= ensures the expensive initialization runs only once. This is more efficient than an unconditional assignment that always creates a new object.
There is no runtime cost beyond the null check itself, which is a simple comparison. The operator compiles to efficient IL that performs a null check and a conditional branch.
When to Use It and When to Avoid It
Use ??= when you want to assign a fallback value only if the current value is null, and the fallback is cheap to compute or has no side effects. It is ideal for lazy initialization, default configuration values, and ensuring collections are instantiated before use.
Avoid ??= when the assignment logic involves more than a simple fallback, such as when the right side depends on the current value or requires a conditional check. In those cases, an explicit if statement is clearer and less error-prone.
Also consider readability for your team. While ??= is concise, some developers may not be familiar with it. If your codebase targets older C# versions, you cannot use it at all. The operator requires C# 8.0 or later.