What do two question marks together mean in C#?
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.
回答1
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.)
Question mark and colon in statement. What does it mean?
This is the conditional operator expression.
(condition) ? [true path] : [false path];
For example
string value = someBooleanExpression ? "Alpha" : "Beta";
So if the boolean expression is true, value will hold "Alpha", otherwise, it holds "Beta".
For a common pitfall that people fall into, see this question in the C# tag wiki.
这种形式的写法,filter.ClaimStatus == null ? true : vatClaimOverview.ClaimStatus == filter.ClaimStatus
可以转换成filter.ClaimStatus == null || vatClaimOverview.ClaimStatus == filter.ClaimStatus