Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why unchecked not working on byte? [duplicate]

Tags:

c#

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?

like image 839
A.s. Bhullar Avatar asked Oct 23 '25 18:10

A.s. Bhullar


1 Answers

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
}
like image 67
Jon Skeet Avatar answered Oct 26 '25 07:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!