I have a code:
static short Sum(short a, short b)
{
return a + b;
}
And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
I have a code:
static short Sum(short a, short b)
{
return a + b;
}
And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
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;
When you add two shorts together, they can add up to more than the allowed value of a short, but an OK value for an int
. This is pretty much what Eric Lippert says in his answer here.
Aside: Why is that not the case for adding two int
s returning a long
? Eric addresses that too:
In a world where integer arithmetic wraps around it is much more sensible to do all the calculations in int, a type which is likely to have enough range for typical calculations to not overflow.
Because of that, the +
operator defined on adding two short
s returns an int
.
This is why you are getting the compile time error - you are returning an int
where you are specifying a short
return type`.
You can explicitly cast the result to short
if you know that the addition will always result in a short
:
static short Sum(short a, short b)
{
return (short)(a + b);
}
Jon Skeet has explained in detail why your code doesn't work, but he hasn't listed what you need to do in order for it to compile. You can use the following:
static short Sum(short a, short b)
{
return (short)(a + b);
}