Quoted from this MSDN blog post:
byte b = 32; byte c = 240; int i = b +
c; // what is i?
In this fantasy world, the value of i
would be 16! Why? Because the two
operands to the + operator are both
bytes, so the sum "b+c" is computed as
a byte, which results in 16 due to
integer overflow. (And, as I noted
earlier, integer overflow is the new
security attack vector.)
Similarly,
int j = -b;
would result in j having the value 224
and not -32, for the same reason.
Is that really what you want?
...
So no matter how you slice it, you're
going to have to insert annoying
casts. May as well have the language
err on the side of safety (forcing you
to insert the casts where you know
that overflow is not an issue) than to
err on the side of silence (where you
may not notice the missing casts until
your Payroll department asks you why
their books don't add up at the end of
the month).
Also, it's worth noting that adding in these casts only means extra typing, and nothing more. Once the JIT (or possibly the static compiler itself) reduces the arithmetic operation to a basic processor instruction, there's nothing clever going on - it's just whether the number gets treated as an int
or byte
.
This is a good question, however... not at all an obvious one. Hope that makes the reasons clear for you now.