The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.0, Perl as of version 5.10, Swift, and PHP 7.0.0. While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. This behavior allows a default value to be defined for cases where a more specific value is not available. In contrast to the ternary conditional if operator used as x ? x : y, but like the binary Elvis operator used as x ?: y, the null coalescing operator is a binary operator and thus evaluates its operands at most once, which is significant if the evaluation of x has side-effects. In Bourne shell (and derivatives), "If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted": #supplied_title='supplied title' # Uncomment this line to use the supplied title title=title" # prints: Default title In C#, the null coalescing operator is ??. It is most often used to simplify expressions as follows: possiblyNullValue ?? valueIfNull For example, if one wishes to implement some C# code to give a page a default title if none is present, one may use the following statement: string pageTitle = suppliedTitle ?? "Default Title"; instead of the more verbose string pageTitle = (suppliedTitle != null) ? suppliedTitle : "Default Title"; or string pageTitle; if (suppliedTitle != null) { pageTitle = suppliedTitle; } else { pageTitle = "Default Title"; } The three forms result in the same value being stored into the variable named pageTitle. suppliedTitle is referenced only once when using the ?? operator, and twice in the other two code examples.
Martin Odersky, Philipp Haller
Anastasia Ailamaki, Miguel Sérgio De Oliveira Branco, Thomas Heinis, Manolis Karpathiotakis, Ioannis Alagiannis