Null coalescing operator
??
is an Operator (programming) that is part of the syntax for a basic conditional expression in several programming languages, specifically C#.
Conditional assignment
?:
is most frequently used to simplify null expressions as follows:
possibly null value ?? value if null
The possibly null value is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value if null if possibly null value is null, but possibly null value otherwise. This is similar to the way ternary operators (?:
statements) work in functional programming languages.
This operator's most common usage is to minimize the amount of code used for a simple null check. (In this case, the expression is converted into a statement by appending a semicolon ; to the expression.) For example, if we wish to implement some C# code to give a page a default title if none is present, we may use the following statement:
string PageTitle = suppliedTitle ?? "Default Title";
instead of the more verbose
string PageTitle = suppliedTitle == null ? "Default Title" : suppliedTitle;
or even worse
string PageTitle; if (suppliedTitle == null) PageTitle = "Default Title"; else PageTitle = suppliedTitle;
The three forms are equivalent.