The compiler has an implicit conversion from a constant expression to various primitive types (so long as the value is within the appropriate range), but here the expression isn't constant - it's just an int expression. It's pretty much the same as:
short s;
s = CallSomeMethodReturningInt32();
as far as the compiler is concerned.
There are two options - you could cast the whole expression, or cast each of the latter two operands:
short s = (EitherTrueOrFalse()) ? (short) 0 : (short) 1;
to make the overall expression type short
. In this particular case, it's a pity that there isn't a numeric literal suffix to explicitly declare a short
literal. Apparently the language designers did consider this, but felt it was a relatively rare situation. (I think I'd probably agree.)
The part about implicit constant conversions is from the C# 3.0 spec section 6.1.8:
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.