C# Null Coalescing Operator (??) is a powerful feature that allows developers to handle null values gracefully by providing a default value.
result = value1 ?? value2;
If value1 is not null, result is value1
If value1 is null, result is value2
Multiple ?? chain operators are used to provide multiple fallback values.
string? first = null;
string? second = null;
string third = "Final Value";
string result = first ?? second ?? third;
Console.WriteLine(result); // Output: "Final Value"
Starting with C# 8.0, the null-coalescing assignment operator (??=) can be used to assign a value to a variable if it is currently null
string? name = null;
name ??= "Default Name";
Console.WriteLine(name); // Output: "Default Name"
Advantages:
- Cleaner Code: Reduces the need for explicit if checks for null.
- Safe Fallbacks: Ensures default values in case of null.
- Improves Readability: Code is more concise and expressive.