Casting for a byte in C #

Possible duplicate:
What happens when you send from a short byte in C #?

Can someone explain what happens when passing a value to a byte if it is outside the range of the min / max byte? It seems to take an integer value and modulo with 255. I am trying to understand the reason why this does not raise an exception.

int i = 5000; byte b = (byte)i; Console.WriteLine(b); // outputs 136 
+8
casting c # byte
source share
5 answers

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, the conv.u1 operator will be used, which will truncate the higher order bits if overflow occurs when converting int to byte, (See the comments section in conv.u1 ).

| 88 |

which is 136 in decimal notation

+7
source share

What happens is that the system throws the most significant bytes to make it usable. Take a look at https://stackoverflow.com/a/16626944/ for a pretty good explanation of what is happening.

+4
source share

I am trying to understand the reason why this does not raise an exception.

Because the default setting for checking overflow is disabled.

Try it, he will throw:

 checked { int i = 5000; byte b = (byte)i; Console.WriteLine(b); } 

Short form:

 int i = 5000; byte b = checked ( (byte)i ); Console.WriteLine(b); 
+3
source share

You get 5000%256 = 136 , as always with overfull.

+1
source share

This is also explained on MSDN. Use checked () to throw an exception if an overflow occurs. Also read the following: MSDN: Chapter 5: Additional Variable Information>

0
source share

All Articles