When you specify the return Type, and the ternary values
that may be returned are of different Types, the compiler must check if a Type conversion is possible.
These work because the compiler can determine there is a conversion possible:
bool boolVal = true;
Animal a1 = boolVal ? new Dog() : (Animal) new Cat();
Animal a2 = boolVal ? (Animal) new Dog() : new Cat();
With your example using Type 'short: what you observe is partly due to the fact that 'short has no literal character that can be appended to it to indicate the Type, as other integral Types allow ... like 'u or 'U for UInt or ULong: [
^].
These work:
bool randomBool = true;
short someRandomVal = 5;
var s1 = randomBool ? 0 : someRandomVal;
var s2 = randomBool ? someRandomVal : 0;
short s3 = randomBool ? someRandomVal : (short) 0;
Int32 s4 = randomBool ? someRandomVal : 0;
Int32 s5 = randomBool ? 0 : someRandomVal;
Keep in mind that an integral numeric value can always be converted/represented to/in an integral Type with "more precision" ... i.e., more bits, greater range ... without loss of information.