C# Console.WriteLine prints a Char type as Integer [duplicate]

≡放荡痞女 提交于 2019-12-11 13:42:55

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48351313/c-sharp-console-writeline-prints-a-char-type-as-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!