Why Ternary Operator Doesnt Support Nullable Types

Nullable types and ternary operators are around for many years now and may be not everybody know that ternary operator doesn’t support assigning null values to nullable types. There is also a bug logged in the “connect” site and it is closed by design.

To understand the real reason for the design, I got in touch with Mads Torgersen, Alex Turner and Anson Horton; the top shots of the Visual Studio team. So this is what is the response I got from them.

Lets assume the below snippet

type? variable = condition ? x : y;

Below are the possible situation the condition will be compiled without any issues.

  • X and Y belong to the same type.
  • Type of X and Y should be implicitly conversible to each other.
  • Type of variable should be implicitly conversible to both X and Y.

Now considering a nullable variable snippet.

double? result = condition ? 100 : null;

The above expression gives a compiler error “Error 3 Type of conditional expression cannot be determined because there is no implicit conversion between ‘<null>’ and ‘int’ “. This is due to the reason that a null value doesn’t have an implicit conversion to integer; in our case 100.

As a developer, I can hear your cry saying that “I don’t care about the conversion restrictions values, all I worry is whether I can assign the true and false values to the variable”. In our case both 100 and null can be assigned to the variable “result” and logically it doesn’t make sense about the error 🙂

So here is what the reply I got from the team; Though the error is by design, they do acknowledge that it is a very common scenario and guess what this way of coding might be allowed in the future versions of C#.

Till then below is your work around.

double? result = condition ? 100 : default(double?);

 

Why Ternary Operator Doesnt Support Nullable Types

Leave a Reply

Scroll to top