Is there anyone able to explain me this strange behavior?
int i = 0x1234;
byte b1 = (byte)i;
byte b2 = (byte)0x1234; //error: const value
This is not a strange behaviour, the valid range for a variable of the byte data type is 0-255
but when you convert HEX 0x1234
value into decimal system you got 4660
.
So unchecked used to control the overflow-checking integral-type arithmetic operations and conversions.
You can find that unchecked
often used in GetHashCode()
implementation which does numeric operations to calculate the final hash code.
To summarize you should use unchecked
when the final result value of integer-type operations is not matter but overflow could happen.