The first two are constant expressions, the last one isn't.
The C# specification allows an implicit conversion from int to short for constants, but not for other expressions. This is a reasonable rule, since for constants the compiler can ensure that the value fits into the target type, but it can't for normal expressions.
This rule is in line with the guideline that implicit conversions should be lossless.
6.1.8 Implicit constant expression conversions
An implicit constant expression conversion permits the following conversions:
- A constant-expression (§7.18) 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.
- A constant-expression of type
long
can be converted to type ulong
, provided the value of the constant-expression is not negative.
(Quoted from C# Language Specification Version 3.0)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…