1) Is UNCHECKED operator in effect only when expression inside UNCHECKED context uses an explicit cast ( such as byte b1=unchecked((byte)2000); ) and when conversion to particular type can happen implicitly? I’m assuming this since the following expression throws a compile time error:
byte b1=unchecked(2000); //compile time error
2) a) Do CHECKED and UNCHECKED operators work only when resulting value of an expression or conversion is of an integer type? I’m assuming this since in the first example ( where double type is being converted to integer type ) CHECKED operator works as expected:
double m = double.MaxValue;
b=checked((byte)m); // reports an exception
, while in second example ( where double type is being converted to a float type ) CHECKED operator doesn’t seem to be working. since it doesn’t throw an exception:
double m = double.MaxValue;
float f = checked((float)m); // no exception thrown
b) Why don’t the two operators also work with expressions where type of a resulting value is of floating-point type?
2) Next quote is from Microsoft’s site:
The unchecked keyword is used to control the overflow-checking context for integral-type arithmetic operations and conversions
I’m not sure I understand what exactly have expressions and conversions such as unchecked((byte)(100+200)); in common with integrals?
Thank you
No. All operations inside the unchecked operator are unchecked, unless of course the unchecked operator then contains a checked operator.
The checked and unchecked operators only have an observable effect on integral types, yes.
Double and float types have infinity, negative infinity and NaN values that can be used as the result of an overflowing operation. There are no “unassigned” values in any integral type that are reserved for “error” situations like this. Double and float can signal the error condition through their values; integers cannot. Therefore you need to be able to turn on some signalling mechanism for integer errors if you want to detect overflows.
Correct. I note that this answers your first two questions.
100 is of integral type. 200 is of integral type. Their sum is of integral type. And byte is an integral type. Everything in that expression is of integral type.
You’re welcome.