This question already has an answer here:
I dont understand why is this printing char data type once as char, other time as integer
static void Main(string[] args)
{
char x = 'A';
int i = 0;
Console.WriteLine(x); // A
Console.WriteLine(true ? x : 0); // 65 ???
Console.WriteLine(false ? i : x); // 65 ???
Console.ReadLine();
}
I would expect output to be A, A, A
but the output of above is A, 65, 65
. Why?
The ternary/conditional operator
?
requires all of the following three operands:The return value will always be of the same type; that is why #2 and #3 must be the same type.
If the third operand isn't the same type as the second operand, the compiler will look for an implicit cast and use it if possible.
So when you write
it is exactly the same as
...and will always return an
int
.If this were not the case, the result of the
?
could not be assigned to a strongly typed variable, which would be a serious obstacle.Also, you cannot write something like this:
...because there is no implicit cast from "A" to integer.