How to Use the Null-Coalescing Operator in C
The null-coalescing operator in C# provides a concise way to handle
null values by returning a fallback value when an
expression evaluates to null. This article covers the
syntax and mechanics of the standard null-coalescing operator
(??), demonstrates how to chain multiple checks together,
explores the null-coalescing assignment operator (??=), and
illustrates common patterns such as pairing it with the null-conditional
operator (?.).
The Standard
Null-Coalescing Operator (??)
The null-coalescing operator is represented by two question marks
(??). It evaluates the left-hand operand: if the value is
not null, it returns that value; if the value is
null, it evaluates and returns the right-hand operand.
Syntax
result = leftOperand ?? rightOperand;Example
string? userInput = null;
string displayName = userInput ?? "Guest";
Console.WriteLine(displayName); // Output: GuestIf userInput contains a valid string (e.g.,
"Alice"), displayName receives
"Alice". Because userInput is
null, the program falls back to "Guest".
Chaining Multiple Operators
You can chain multiple ?? operators to check a sequence
of variables until a non-null value is found. Evaluation stops at the
first non-null operand.
Example
string? preferredName = null;
string? officialName = null;
string fallbackName = "Anonymous";
string finalName = preferredName ?? officialName ?? fallbackName;
Console.WriteLine(finalName); // Output: AnonymousThe Null-Coalescing
Assignment Operator (??=)
Introduced in C# 8.0, the null-coalescing assignment operator
(??=) assigns the value of its right-hand operand to its
left-hand operand only if the left-hand operand evaluates to
null.
Syntax
variable ??= defaultValue;Example
List<int>? numbers = null;
// Initializes the list only if it is null
numbers ??= new List<int>();
numbers.Add(10);
Console.WriteLine(numbers.Count); // Output: 1If numbers is already initialized, the right-hand side
is not executed, preventing unnecessary object allocations.
Combining
?? with the Null-Conditional Operator
(?.)
A common practice in C# is pairing the null-conditional operator
(?.) with the null-coalescing operator (??) to
navigate nested objects safely while providing a guaranteed default
value.
Example
public class Profile
{
public string? Bio { get; set; }
}
public class User
{
public Profile? Profile { get; set; }
}
// Usage
User? user = null;
// If user or Profile or Bio is null, returns "No bio available."
string bio = user?.Profile?.Bio ?? "No bio available.";
Console.WriteLine(bio); // Output: No bio available.This combination prevents NullReferenceException errors
without requiring verbose nested if statements.