Checked and Unchecked operators don't seem to be working when...

Posted by flockofcode on Stack Overflow See other posts from Stack Overflow or by flockofcode
Published on 2010-06-15T19:30:19Z Indexed on 2010/06/15 19:32 UTC
Read the original article Hit count: 193

Filed under:

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

© Stack Overflow or respective owner

Related posts about c#