Alex Rivera | Logout

In C# why can't a conditional operator implicitly cast to a nullable type

Asked 2008-10-20T23:04:11.337
32

I am curious as to why an implicit cast fails in...

int? someValue = SomeCondition ? ResultOfSomeCalc() : null;

and why I have to perform an explicit cast instead

int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;

It seems to me that the compiler has all the information it need to make an implicit casting decision, no?

Edit
Report

1 Answer

15

I also am annoyed that it can't infer the type based on the assignment, especially when it's a value type. There are reasons though when you get into object heirarchies.

If "ResultOfSomeCalc()" returned a "int?", then this would work. C# needs to figure out the type regardless of what is to the left of the assignment. So you are telling it that you'll return a null or an int - and the logic in the compiler doesn't exist to have it substitute a Nullable as a common denominator.

Notice that these variants DO work, and it may help you understand:

object someValue = true ? new Nullable<int>(ResultOfSomeCalc()) : null;

object someValue = true ? (int?)ResultOfSomeCalc() : null;

Hope this helps.

answered 2008-10-20T23:14:39.240

Your Answer