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?
You've misunderstood the purpose of unchecked
. It has two effects:
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
}
See more on this question at Stackoverflow