Re: why does adding 2 bytes together result in an int?




"moondaddy" <moondaddy@xxxxxxxxxxxxx> wrote in message
news:Ofz5SwhPGHA.2300@xxxxxxxxxxxxxxxxxxxxxxx
my understanding is that the max value of a byte is 255. Therefore, why
does the following code get a compile error?

byte val1 = 10;
byte val2 = 23;
byte ttl;
ttl = val1 + val2; //this line wont compile

compile error: Cannot implicitly convert type 'int' to 'byte'.

val1 + val2 = 33 which is still in the range of a byte. therefore, why do
I need to convert ttl into an int?

There is no really good reason.

What Jon said about the IL opcodes is true but irrelevant - the compiler
could just cast the result back to byte for you.

What others said about 128 + 128 is true but inconsistent - the same
arguments could be applied to int or long.

I agree that it is a total pain and either an oversight or excess nannying
by MS but that's the way that it is.

On the plus side it would break no code to change it so MS might do it if
enough people complain.

P.S. It's the same for short - but who uses short?


.



Relevant Pages


Loading