When this code finishes, what is the result of myObject
?
object myObject = "something";
object yourObject = null;
myObject = null ?? yourObject;
When this code finishes, what is the result of myObject
?
object myObject = "something";
object yourObject = null;
myObject = null ?? yourObject;
myObject will be null
This gets transalated 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.