开发者

What do we mean by ? OR ???

Someone tell me the difference and example why we use these. I know its for N开发者_如何学GoULL values.


x ? a : b means if (x == true) then a else b

x ?? y means if (x != null) then x else y

but with a twist since both are expressions rather than statements like the IF.

That allow you to write var z = x ? a : b; to combine declaration and assignment in one line instead of the multi-line alternative:

type z;
if (x == true)
  z = a;
else
  z = b;

Type? is a shorthand for Nullable<Type>


? is a ternary operator, officially named the conditional operator in C#.

?? is the null coalescing operator

The conditional operator is useful for short, concise if/else statements

The null coalescing operator is useful for returning one value if it is not null, otherwise returning another value (the value on the right side of the operator)


there are two different operator which use '?'

  • Conditional Operator: condition?then:else if condition is true then 'then part' else 'else part', this operator is like if-else.

  • null-coalescing operator: The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand. // y = x, unless x is null, in which case y = -1. int y = x ?? -1;


The first one is a Ternary Operator or Conditional Operator

The second one is a Null Coalescing Operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜