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#,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 first operand if it exists and is not null.
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 C#, the null coalescing operator is ??
. It is most often used to simplify null expressions as follows:
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:
instead of the more verbose
or
The three forms are logically equivalent.
The operator can also be used multiple times in the same expression:
Once a non-null value is assigned to number, or it reaches the final value (which may or may not be null), the expression is completed.
As of ColdFusion 11,Railo 4.1,CFML supports the null coalescing operator as a variation of the ternary operator, ?:
. It is functionally and syntactically equivalent to its C# counterpart, above. Example:
Clojure's or macro works similarly.
You can also chain values.