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?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • 2
    This is a duplicate of http://stackoverflow.com/questions/2450866 which was in turn a duplicate of http://stackoverflow.com/questions/858080. See http://stackoverflow.com/questions/2215745/conditional-operator-cannot-cast-implicitly/2215959#2215959 for an analysis of the issue. – Eric Lippert May 04 '10 at 17:18

3 Answers3

105

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;
LukeH
  • 263,068
  • 57
  • 365
  • 409
21

You need to use the default() keyword rather than null when dealing with ternary operators.

Example:

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

Alternately, you could just cast the null:

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

Personally I stick with the default() notation, it's just a preference, really. But you should ultimately stick to just one specific notation, IMHO.

HTH!

code4life
  • 15,655
  • 7
  • 50
  • 82
1

The portion (true ? null : 0) becomes a function in a way. This function needs a return type. When the compiler needs to figure out the return type it can't.

This works:

int? i;
i = (true ? null : (int?)0);
Arulkumar
  • 12,966
  • 14
  • 47
  • 68
Andrey
  • 1,247
  • 11
  • 30