Required casting using C# ternary conditional operator

我们两清 提交于 2019-11-28 13:35:33
Jakub Lortz

The expression test ? val : 0 compiles just fine. You get an error in this line, because the type of this expression is int and you're trying to assign it to a short variable. That requires an explicit cast. From C# language spec:

If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

Another question is why, for example, a literal 0 can be assigned to a short variable without a cast:

short i = 0;

And a result of ternary operator has to be cast:

bool test = new Random().NextDouble() >= 0.5;
short val = 5;
short i = (short)(test ? val : 0);

The reason is that first assignment is evaluated at compile-time, because it consists only of constants. In such case, the implicit constant expression conversion rules apply:

• A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

The ternary operator can also be evaluated at compile time if all operands are constants:

short i = true ? 0 : int.MaxValue;

In any other case, the stricter runtime conversion rules apply. All 3 statements below give compile errors:

int intVal = 0;
short shortVal = 0;
bool boolVal = true;

short i = true ? 0 : intVal;
short j = true ? shortVal : 0;
short k = boolVal ? 0 : 0;

For reference you can see Eric Lippert's comments.

The second example would require treating Nullable<> as a special case, like you already noticed.

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