views:

68

answers:

3

When this code finishes, what is the result of myObject?

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

myObject = null ?? yourObject;
+2  A: 

myObject will be null

This gets transalated to -

if (null == null)
    myObject = yourObject;
else
    myObject = null;
Sachin Shanbhag
+1  A: 

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.

Dismissile
@Dismissile, of course my example was very simplistic and non-realistic. Thank you for your explanation.
Brad
Yeah I realize that. The point of the coalesce operator is to provide a value to use when something is null...more than likely so you don't get a null reference exception if you try and use the value. An example: someString = (someString ?? "").ToLower();
Dismissile
It is also useful for assigning nullable types to non-nullable types. Example: int? x = 1; int y = x ?? -1; If you tried to assign y to x without using ?? or doing x.Value you would get an error. And if you did x.Value and the value is null then you are also in trouble.
Dismissile
+1  A: 

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.

pst