Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 330
Tim Jarvis Avatar asked Oct 20 '08 23:10

Tim Jarvis


People also ask

What is %A in C?

Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A.

How operator is used in C?

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.


1 Answers

The relevant section of the C# 3.0 spec is 7.13, the conditional operator:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

If X and Y are the same type, then this is the type of the conditional Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. Otherwise, no expression type can be determined, and a compile-time error occurs.

like image 118
Brian Liang Avatar answered Oct 07 '22 14:10

Brian Liang