views:

412

answers:

4
double? test = true ? null : 1.0;

In my book, this is the same as

if (true) {
  test = null;
} else {
  test = 1.0;
}

But the first line gives this compiler error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'double'.

+6  A: 
double? test = true ? (double?)null : 1.0;

will work. That's because there is no conversion from the type of the first expression (null) to the type of the second expression (double).

David Schmitt
Hehe, same answer just other way around, now a confused :)
leppie
Surprise, both ways work :)
leppie
"Cannot convert null to 'double' because it is a non-nullable value type"
Robbert Dam
This doesn't compile!
bruno conde
darn, missed 75 rep due to forgetting the '?'. :-)
David Schmitt
+14  A: 
double? test = true ? null : (double?) 1.0;
leppie
Thanks, this works!
Robbert Dam
A: 

Because null is not, actually, implicitly convertable to a double?. Funny as that sounds.

double? test = true ? (double?) null : 1.0;
J. Steen
Been said already.
leppie
I was typing it at the same time as everyone else.
J. Steen
This doesn't compile!
bruno conde
Yes, it should be double?, my extreme bad.
J. Steen
I like how the other similar answer got eight upvotes. ;)
J. Steen
+1  A: 

The left hand side of the assignment is not used when deducing the type of an ?: expression.

In b ? A : B, the tyes of A and B must either be the same, or one must be implicitly convertible to the other.

James Hopkin
There is some subtlety here -- is it that the type of A must be convertible to the type of B, or that A must be convertible to the type of B?The compiler actually gets it wrong! See this posthttp://blogs.msdn.com/ericlippert/archive/2006/05/24/type-inference-woes-part-one.aspxfor details.
Eric Lippert