20

Possible Duplicates:
Why can't I set a nullable int to null in a ternary if statement?
Nullable types and the ternary operator. Why won't this work?

Whats wrong with the below

public double? Progress { get; set; }
Progress = null; // works
Progress = 1; // works
Progress = (1 == 2) ? 0.0 : null; // fails

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

Community
  • 1
  • 1
Jiew Meng
  • 81,093
  • 172
  • 469
  • 784
  • dup http://stackoverflow.com/questions/2766932/why-cant-i-set-a-nullable-int-to-null-in-a-ternary-if-statement – pavanred Nov 22 '10 at 12:57

2 Answers2

34

When using the ?: operator, it has to resolve to a single type, or types that has an implicit conversion between them. In your case, it will either return a double or null, and double does not have an implicit conversion to null.

You will see that

Progress = (1 == 2) ? (double?)0.0 : null;

works fine, since there is an implicit conversion between nullable double and null

AustinWBryan
  • 3,081
  • 3
  • 18
  • 38
Øyvind Bråthen
  • 56,684
  • 27
  • 122
  • 146
0

The double is 0.0 in this case

Progress = (1 == 2) ? (double?)0.0 : null; // works
Colin Pickard
  • 44,639
  • 13
  • 95
  • 146