Null-Coalescing Operator
Closely related to the conditional operator is the well-sounding null-coalescing operator, which was introduced in C# 2.0 as part of the whole nullability straightening mission. When dealing with reference types or nullable value types, it sometimes makes sense to be able to supply a default value as a substitute for null. That’s precisely what the null-coalescing operator provides:
int? deposit = GetDeposit(user);AddToAccount(user, deposit ?? 0);
Written as an infix ?? operator, the null-coalescing operator first evaluates the left operand. If it results in the null reference (for a reference type) or a nullable value with no value set (HasValue is false), the right operand is evaluated to produce the result; otherwise, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access