And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
It's just the way the language is defined. The + operator on integer types is defined for:
static uint op +(uint x, uint y)
static int op +(int x, int y)
static ulong op +(ulong x, ulong y)
static long op +(long x, long y)
Operands are promoted as required.
Now as for the reasons why it's defined that way - I don't know, to be honest. I don't buy the argument of "because it could overflow" - that would suggest that byte + byte
should be defined to return short
, and that int + int
should return long
, neither of which is true.
I've heard somewhere that it could be performance related, but I wouldn't like to say for sure. (Perhaps processors typically only provide integer operations on 32 and 64 bit integers?)
Either way, it doesn't really matter why it's the case - it's just the rules of the language.
Note that the compound assignment operators have an implicit conversion back to the relevant type, so you can write:
short x = 10;
short y = 20;
x += y;