Coder Perfect

Why is’the ternary operator and nullable types? 10: Is it illegal to use the word “null”? [duplicate]

Problem

I just came across a weird error:

private bool GetBoolValue()
{
    //Do some logic and return true or false
}

Then there’s another method, which goes like this:

int? x = GetBoolValue() ? 10 : null;

Simply set 10 to the Nullableint x if the method returns true. Otherwise, set the nullable int to null. The compiler, on the other hand, complains:

Am I losing my mind?

Asked by BFree

Solution #1

The right-hand expression is evaluated first by the compiler:

GetBoolValue() ? 10 : null

The ten is a literal int (not int?) Null, on the other hand, is null. The error message is due to the fact that there is no implicit conversion between the two.

Because there is an implicit conversion between int? and null (#1) and int and int? (#2, #3), changing the right-hand expression to one of the following compiles.

GetBoolValue() ? (int?)10 : null    // #1
GetBoolValue() ? 10 : (int?)null    // #2
GetBoolValue() ? 10 : default(int?) // #3

Answered by LukeH

Solution #2

Try this:

int? x = GetBoolValue() ? 10 : (int?)null;

What is happening is that the conditional operator is unable to detect the expression’s “return type.” Because the compiler has already determined that 10 is an int, it has also determined that the return type of this expression will be an int. It complains because an int (the third operand of the conditional operator) can’t be null.

By casting the null to a Nullable we are telling the compiler explicitly that the return type of this expression shall be a Nullable. You could have just as easily casted 10 to int? and gotten the same result.

Answered by Andrew Hare

Solution #3

Try this:

result = condition? int? result = condition? default(int? ); default(int? ); default(int? ); default(

Answered by Unknown

Solution #4

In a very subtle and interesting (to me) way, the Microsoft implementation of the C# compiler gets the type analysis of the conditional operator wrong. Type inference woes, part one is my article on it (2006-05-24).

Answered by Eric Lippert

Solution #5

Consider one of the following:

int? x = GetBoolValue() ? (int?)10 : null;

int? x = GetBoolValue() ? 10 : (int?)null;

Answered by John Gietzen

Post is based on https://stackoverflow.com/questions/858080/nullable-types-and-the-ternary-operator-why-is-10-null-forbidden