Friday, February 13, 2009

Nullable Types And The Ternary Operator

Lately I have been wondering why this will not compile in C# 2.0 Visual Studio 2005: int? x = ({expression} ? null : 1); The error I get is: Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'int' I would assume that the compiler "knows" that x can be null, or any int. However, it can't cast null to an int here. Probably becuase it is evaluating the ternary expression first. This works: int? x; if ({expression}) x = null else x = 1 Probably because it evaluates the expression first then the assignments. Anyways a work around (suggested by Andy) is: int? x = ({expression} ? (int?)null : 1); Which really shouldn't be nessecary. {6230289B-5BEE-409e-932A-2F01FA407A92}

1 comment:

  1. You can actually cast either result to (int?) and it fixes the error. I think the issue isn't that both results (1 or null) can be converted to your "int? x =" as in the case of your if() {} else {} statement, but that the compiler is trying to enforce that both results are compatible with each other.