Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats wrong with setting nullable double to null? [duplicate]

Tags:

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>'

like image 210
Jiew Meng Avatar asked Nov 22 '10 12:11

Jiew Meng


People also ask

Does HasValue check for 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.

Can double be null C#?

Short answer: You can't. A double can only contain a valid double-precision floating point value.

Is null equal to null C#?

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.

What is the purpose of a nullable type?

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 .


1 Answers

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

like image 185
Øyvind Bråthen Avatar answered Oct 13 '22 06:10

Øyvind Bråthen