21

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
  • 84,767
  • 185
  • 495
  • 805
  • 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

35

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,249
  • 3
  • 24
  • 42
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
0

The double is 0.0 in this case

Progress = (1 == 2) ? (double?)0.0 : null; // works
Colin Pickard
  • 45,724
  • 13
  • 98
  • 148