Alex Rivera | Logout

Why can't I set a nullable int to null in a ternary if statement?

Asked 2010-05-04T16:06:09.137
50

The C# code below:

int? i;
i = (true ? null : 0);

gives me the error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'

Shouldn't this be valid? What am i missing here?

Edit
Report

1 Answer

106

The compiler tries to evaluate the right-hand expression. null is null and the 0 is an int literal, not int?. The compiler is trying to tell you that it can't determine what type the expression should evaluate as. There's no implicit conversion between null and int, hence the error message.

You need to tell the compiler that the expression should evaluate as an int?. There is an implicit conversion between int? and int, or between null and int?, so either of these should work:

int? x = true ? (int?)null : 0;

int? y = true ? null : (int?)0;
answered 2010-05-04T16:07:22.943

Your Answer