Possible Duplicate:
Integer summing blues, short += short problem
I feel dumb that this is happening, but I have never had this happen before. I am trying to do the following:
foreach (short a in answers)
{
if (a != myConstants.NOTCOMPLETE_SHORT)
{
result = result + a;
}
else
{
empty = true;
break;
}
}
answers is an array of shorts. intellisense is telling me that result + a is an int and I can’t assign it to a short.
I have to be missing something very fundamental here but not allowing two shorts to be added together and assigned to a short variable just seems weird.
Since a
shortis a 16bit Integer, if you added, say,32,000and32,000(both validshorts), you’d get64,000which is not a validshortasInt16.MaxValueis32767.Thus, the addition operator must return a 32bit Int to prevent the result from possibly overflowing.
UPDATE:
For fun, I just tried this in PowerShell:
So looks like an
Int32can cast to aDoubleif needed.I’m gonna go out on a limb and say bounds checking during addition is more expensive, and thus should only be done if there’s a likely chance of an overflow (like two bytes or two shorts) especially when they’re possibly using the same amount of memory anyway. I think that’s just the way the language was designed.