Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the ternary operator find cast type depending on value being looked for?

Tags:

c#

A question here raised a question for me:

Ternary operations in c#, say x = y ? a : b, use the type of either a or b to determine the type of the ternary expression. Why doesn't it use the type of x? In any given situation, isn't there an expected return type that it can use?

EDIT: For the sake of clarity, when I say

Why doesn't it use the type of x?

I suppose I mean

Why doesn't it first try to use the type of x?

As the documentation states:

  • If X and Y are the same type, then this is the type of the conditional expression.
  • Otherwise, if an implicit conversion (Section 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 (Section 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.

Could this process start with:

  • If the resolution type is unambiguous, then it is the type of the conditional expression.
like image 956
MirroredFate Avatar asked Sep 12 '13 22:09

MirroredFate


1 Answers

"In any given situation, isn't there an expected return type that it can use?"

No. Consider for example:

string s = Convert.ToString(y ? a : b);

There are multiple overloads of the ToString method that takes different data types. The compiler needs to know what the type of the expression is to know which overload to use.

like image 86
Guffa Avatar answered Nov 09 '22 17:11

Guffa