Why can I pass 1 as a short, but not the int variable i?
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 typesbyte
,byte
,short
,ushort
,uint
, orulong
, 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 typeulong
, provided the value of the constant-expression is not negative.
(Quoted from C# Language Specification Version 3.0)
There is no implicit conversion from int
to short
because of the possibility of truncation. However, a constant expression can be treated as being of the target type by the compiler.
1
? Not a problem: it’s clearly a valid short
value. i
? Not so much – it could be some value > short.MaxValue
for instance, and the compiler cannot check that in the general case.
an int
literal can be implicitly converted to short
. Whereas:
You cannot implicitly convert nonliteral numeric types of larger storage size to short
So, the first two work because the implicit conversion of literals is allowed.