CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Figure 3-3. Enabling project-wide overflow/underflow data checking
Enabling this setting can be very helpful when you’re creating a debug build. After all of the overflow
exceptions have been squashed out of the code base, you’re free to disable the /checked flag for
subsequent builds (which will increase the runtime performance of your application).
The unchecked Keyword
Now, assuming you have enabled this project-wide setting, what are you to do if you have a block of
code where data loss is acceptable? Given that the /checked flag will evaluate all arithmetic logic, C#
provides the unchecked keyword to disable the throwing of an overflow exception on a case-by-case
basis. This keyword’s use is identical to that of the checked keyword in that you can specify a single
statement or a block of statements.
// Assuming /checked is enabled,
// this block will not trigger
// a runtime exception.
unchecked
{
byte sum = (byte)(b1 + b2);
Console.WriteLine("sum = {0} ", sum);
}
So, to summarize the C# checked and unchecked keywords, remember that the default behavior of
the .NET runtime is to ignore arithmetic overflow/underflow. When you want to selectively handle
discrete statements, make use of the checked keyword. If you wish to trap overflow errors throughout
your application, enable the /checked flag. Finally, the unchecked keyword may be used if you have a
block of code where overflow is acceptable (and thus should not trigger a runtime exception).
107