Possible Duplicate:
What happens when you cast from short to byte in C#?
Can someone explain what's happening when casting a value to a byte, if it's outside the range of min/max byte? It seems to be taking the integer value and modulo it with 255. I'm trying to understand the reason for why this doesn't throw an exception.
int i = 5000;
byte b = (byte)i;
Console.WriteLine(b); // outputs 136
5000 is represented as 4 bytes (int) (hexadecimal)
Now, when you convert it to byte, it just takes the last 1-byte.
Reason: At the IL level, conv.u1 operator will be used which will truncate the high order bits if overflow occurs converting int to byte. (See remarks section in the conv.u1 documentation).
which is 136 in decimal representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With