开发者

What is the result if all parameters in a null coalescing operation are null?

When this code finishes, what is t开发者_如何学编程he result of myObject?

object myObject = "something";
object yourObject = null;

myObject = null ?? yourObject;


myObject will be null

This gets translated to -

if (null == null)
    myObject = yourObject;
else
    myObject = null;


The coalesce operator translates to this:

x ?? y
x != null ? x : y

Therefore what you have:

myObject = null != null ? null : yourObject;

Which is actually pretty pointless since null will always be null.


Just for kicks, here is a small table:

A    ?? B    -> R
---------------------
a    ?? any  -> a; where a is not-null
null ?? b    -> b; for any b
null ?? null -> null; implied from previous

And since ?? is just a (surprise!) right-associated infix operator, x ?? y ?? z --> x ?? (y ?? z). Like && and ||, ?? is also a short-circuiting operation.

...from ?? Operator (C# Reference):

It (??) returns the left-hand operand if it is not null; otherwise it returns the right operand.

...from the C# 3.0 Language reference:

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜