Search code examples
c#charconsole.writeline

C# Console.WriteLine prints a Char type as Integer


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?


Solution

  • The ternary/conditional operator ? requires all of the following three operands:

    1. An expression that evaluates to a boolean
    2. An expression that returns a value of any type
    3. An expression that returns a value of the same type as #2

    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

    var x = flag ? 65 : 'A';
    

    it is exactly the same as

    int x = flag ? (int)65 : (int)'A';
    

    ...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:

    var x = flag ? 65 : "A"; //Notice it's a string and not a char
    

    ...because there is no implicit cast from "A" to integer.