Ran across this line of code:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
What do the two question marks mean, is it some kind of ternary operator? It's hard to look up in Google.
The JavaScript double question mark is also known as the nullish coalescing operator. It's an operator that simply returns the right-side expression when the left side expression is either null or undefined .
The C# double question mark operator ?? is called the null-coalescing operator. It is used to return the left hand side operand of the operator if the value is not null and the right hand side operand if the value is null.
Most likely the '?' is the ternary operator. Its grammar is: RESULT = (COND) ? ( STATEMEN IF TRUE) : (STATEMENT IF FALSE) It is a nice shorthand for the typical if-else statement: if (COND) { RESULT = (STATEMENT IF TRUE); } else { RESULT = (STATEMENT IF FALSE);
The JavaScript double question mark (??) operator is called the nullish coalescing operator and it provides a default value when a variable or an expression evaluates to null or undefined.
It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also ?? Operator - MSDN.
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
expands to:
FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
which further expands to:
if(formsAuth != null) FormsAuth = formsAuth; else FormsAuth = new FormsAuthenticationWrapper();
In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."
Note that you can use any number of these in sequence. The following statement will assign the first non-null Answer#
to Answer
(if all Answers are null then the Answer
is null):
string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;
Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)
Just because no-one else has said the magic words yet: it's the null coalescing operator. It's defined in section 7.12 of the C# 3.0 language specification.
It's very handy, particularly because of the way it works when it's used multiple times in an expression. An expression of the form:
a ?? b ?? c ?? d
will give the result of expression a
if it's non-null, otherwise try b
, otherwise try c
, otherwise try d
. It short-circuits at every point.
Also, if the type of d
is non-nullable, the type of the whole expression is non-nullable too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With