Information Technology Reference
In-Depth Information
Overflow Checking Context
You've seen that explicit conversions have the possibility of losing data and not being able to
represent the source value equivalently in the target type. C# provides you with the ability to
choose whether the runtime should check the result for overflow when making these types of
conversions. It does this through the checked operator and statement.
￿
Whether a segment of code is checked or not is called its overflow checking context .
-
If you designate an expression or segment of code as checked , the CLR will raise an
OverflowException exception if the conversion produces an overflow.
If the code is not checked , the conversion will proceed regardless of whether there is
an overflow.
-
The default overflow checking context is not checked .
￿
The checked and unchecked Operators
The checked and unchecked operators control the overflow checking context of an expression,
which is placed between a set of parentheses. The syntax is the following:
checked ( Expression )
unchecked ( Expression )
For example, the following code executes the same conversion—first in a checked operator
and then in an unchecked operator.
￿In the unchecked context, the overflow is ignored, resulting in the value 208 .
￿In the checked context, an OverflowException exception is raised.
ushort sh = 2000;
byte sb;
sb = unchecked ( (byte) sh ); // Most significant bits lost
Console.WriteLine("sb: {0}", sb);
sb = checked ( (byte) sh ); // OverflowException raised
Console.WriteLine("sb: {0}", sb);
Search WWH ::




Custom Search