4

The unchecked keyword has been explained in MSDN library as:

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions. In an unchecked context, if an expression produces a value that is outside the range of the destination type, the overflow is not flagged.

By definition it works well on int type.

For example:

unchecked
{
   int i=2147483647+10;
}

Here it suppresses the overflow inside unchecked block.(it should be)

But when we apply it on byte it does not work

byte b1=100,b2=100,b3;
unchecked
{
   b3=b1+b2;//error here
}

So whatever is written in unchecked environment should be suppressed.

Why it is giving compile time error?

Or does I not understand unchecked keyword at all?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
A.s. Bhullar
  • 2,680
  • 2
  • 26
  • 32

2 Answers2

9

You've misunderstood the purpose of unchecked. It has two effects:

  • It prevents overflow checking at execution time
  • It allows you to convert constant values which are outside the normal range of the type, as per your first example.

It doesn't change the type of an expression. The type of the expression b1 + b2 is still int, so you still need a cast to convert it to byte. The difference between checked and unchecked in this situation is the execution-time handling of overflow when casting the int back to byte:

byte b1 = 255, b2 = 1;
unchecked
{
   byte b3 = (byte) (b1 + b2);
   // b3 is now 0
}

With checked arithmetic:

byte b1 = 255, b2 = 1;
checked
{
   byte b3 = (byte) (b1 + b2); // OverflowException
}
Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

There is no + operation on bytes. So, b1 + b2 is still int as a result.

Your code works as like;

byte b1 = 100, b2 = 100, b3;
unchecked
{
   b3 = (int)b1 + (int)b2; //error here
}

If you cast to byte the solution, there will be no problem;

byte b1 = 100, b2 = 100, b3;
unchecked
{
    b3 = (byte)(b1 + b2); //There is no error here.
}

Why unchecked not working on byte?

Because unchecked keyword is uses for overflow-checking for integral-type arithmetic and Eric Lippert says;

The various musings below are a reasonable approximation of the design considerations. More generally: I don't think of bytes as "numbers"; I think of them as patterns of bits that could be interpreted as numbers, or characters, or colors or whatever. If you're going to be doing math on them and treating them as numbers, then it makes sense to move the result into a data type that is more commonly interpreted as a number.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364