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)
|00|00|13|88|
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).
|88|
which is 136 in decimal representation