Why can't I use uint a = b == c ? 0 : 1; uint a = b == c ? 0 : 1; ?
Expression Type b == c ? 0 : 1 b == c ? 0 : 1 is int . As shown in this table , there is no implicit conversion from int to uint , so this is not allowed.
Why can I use a = 0 ?
Because there is special handling of numeric types when a value is a constant expression.
From section 6.1.9 of the C # specification:
A constant expression of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong if the value of the constant expression is within the range of the destination type.
A constant expression of type long can be converted to type ulong if the value of the constant expression is not negative.
As indicated in the first mark, a = 0 and a = 1 , both are allowed because 0 and 1 are constant expressions and are real uint values. It basically boils down to the fact that the compiler can easily determine at compile time that these transformations are valid, so it allows them.
By the way, if part of your first example b == c was changed to a constant expression (for example, true ), then the entire conditional expression of the operator will be a constant expression, and the code will compile.
JLRishe Mar 09 '17 at 8:27 2017-03-09 08:27
source share