Why does the conditional operator always return an int in C#? [duplicate]

房东的猫 提交于 2020-01-04 09:21:50

问题


Possible Duplicate:
Conditional operator cannot cast implicitly?

When writing a statement using the conditional operator, if the either of the expressions are numeric values they are always interpreted as int type. This makes a cast necessary to assign a short variable using this operator.

bool isTrue = true;
int intVal = isTrue ? 1 : 2;
short shortVal = isTrue ? 1 : 2;  // Compile error: Cannot implicitly convert type 'int' to 'short'. 

Shouldn't the compiler be able to know that both values are valid short values just as it would in a typical assignment statement(short shortVal = 1;)?


回答1:


It's not that the conditional operator (AKA ternary operator) always returns ints, it's because your literals are ints.

Unfortunately, C# doesn't appear to have a literal specifier for bytes or shorts (they do for longs, though).




回答2:


This is because your 1 and 2 are ints. ?: returns the same type as 2nd and 3rd operands in your case.


Edit: At my VS2008 this works:

short x = true ? 1 : 2;

Did I do something wrong?


Edit: Indeed, the difference was that true was a compile-time constant. For non-constant expressions I got the same error message.



来源:https://stackoverflow.com/questions/2356618/why-does-the-conditional-operator-always-return-an-int-in-c

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