开发者

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

This question already has answers here: Closed 12 years ago.

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 val开发者_JAVA技巧ues are valid short values just as it would in a typical assignment statement(short shortVal = 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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜