I am surprised by the output of the following code
public static void Main(string[] args)
{
char x = 'A';
int i = 0;
Console.WriteLine (true ? x : 0);
Console.WriteLine(false ? i : x);
}
When I was reading the C# interview question I saw this code and the output of above code was
Output
65
65
I am wondering how does that happen.
Can anybody explain me ? Thanks!
'A'
is a char
and has the value of 65
However, there is a technical explanation for why this results in an integer (and not the string representation of a char), you can find it in the ECMA C# specifications
12.15 Conditional operator
The second and third operands, x and y, of the ?: operator control the type of the conditional expression.
- If x has type X and y has type Y then,
- If X and Y are the same type, then this is the type of the conditional expression.
- Otherwise, if an implicit conversion (§11.2) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
- Otherwise, if an implicit enumeration conversion (§11.2.4) exists from X to Y, then Y is the type of the conditional expression.
- Otherwise, if an implicit enumeration conversion (§11.2.4) exists from Y to X, then X is the type of the conditional expression.
- Otherwise, if an implicit conversion (§11.2) 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.
- If only one of x and y has a type, and both x and y are implicitly convertible to that type, then that is the type of the conditional expression.
- Otherwise, no expression type can be determined, and a compile-time error occurs
Example
char Y = 'A';
int X = Y;
Y = X; // compiler error
In short, there is no implicit conversion from int
to char
, yet there is from char
to int
, so it makes sense for the result type to be an int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With