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>'
The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.
Short answer: You can't. A double can only contain a valid double-precision floating point value.
If you think of it from a programming (i.e. pointer reference) point of view then, yes, two references of null have the same pointer value and, since most of the popular languages will fall back to pointer-equality if no custom equality is defined, null does equal null.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With