Two Shorts CAN make an INT so it is not possible to implicitly cast X + Y as a short.
change it to
int z = x + y;
and it will run
Based on comments I am adding the following code sample to clear up some issues:
class BasicMath
{
short s_max = short.MaxValue; // the max value for a short (or an Int16) is 32767
int i_max = int.MaxValue; // the max value for an int (or an Int32) is 2,147,483,647
long l_max = long.MaxValue; // the max value for a long (Int64) is 9,223,372,036,854,775,807
public int AddingShorts(short x, short y)
{
short addedvalues = (short)(x + y);
//yes this will compile and run, but the result of 32767 + 32767 = -2
//short addedShorts = (short)s_max + s_max;
int addedInts = i_max + i_max;
//No, this doesn't require a cast, but it also achieves the spectaclar result of
//2,147,483,647 + 2,147,483,647 = -2
return addedvalues;
//casting a short to an int works implicitly (note the return type here is int, not short)
//still if you pass in values of exceeding 32767 you will end up with -2 because attempting
//cast as a short a value of greater than 32767 results in -2.
}
}
Why does the compiler require short + short to be (at least) an int and does not apply the same rule to ints?
Ask Anders... The fact is this is 'the rule the compiler enforces' on all days ending in "Y"
If you attempt to simply CAST the sum of two shorts as a short, yes it will compile but it is also prone to produce a result you will not be happy with.
Cheers