12

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
Community
  • 1
  • 1
Stealth Rabbi
  • 10,156
  • 22
  • 100
  • 176

5 Answers5

13

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

prashanth
  • 2,059
  • 12
  • 13
5

What's happening is the system is dropping the Most Significant Bytes in order to make it fit. Look at this StackOverFlow answer for a pretty good explanation on what's going on.

Community
  • 1
  • 1
Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • I suppose there's no way to check at compile time, and there's a real incentive not to throw exceptions for conversions for base types. Dropping bits seems like the best of a bunch of bad options. – James Cronen Sep 24 '12 at 21:15
  • Well if you don't explicitly cast it, C# should throw you a compile-time error. For example: `byte b = myInt;`...That should throw an error. Now if you explicitly cast it, like in your example above, no error will be thrown – Icemanind Sep 24 '12 at 21:18
3

I'm trying to understand the reason for why this doesn't throw an exception.

Because the default setting for overflow checking is off.

Try this, it will throw:

checked
{
    int i = 5000;
    byte b = (byte)i;

    Console.WriteLine(b);
}

The short form is:

int i = 5000;
byte b = checked ( (byte)i );    
Console.WriteLine(b);
H H
  • 263,252
  • 30
  • 330
  • 514
1

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

KAction
  • 1,977
  • 15
  • 31
0

It is also explained in MSDN. Use checked() to throw exception if overflow occurs. Also read this: MSDN: Chapter 5: More About Variables

Eiver
  • 2,594
  • 2
  • 22
  • 36