HomeSearch

C# Checked and Unchecked Keywords

Observe the effect of the checked keyword. Checked and unchecked change how overflow is handled.
Checked, unchecked. Checked adds exceptions on number overflows. When a number overflows, its value becomes invalid. Normally, this causes no exception to be thrown.Keywords
Inside a checked context, though, an exception is thrown. With checked, errors can be prevented by catching overflow early. This leads to higher-quality programs.Exception
Checked example. When we execute this program, an OverflowException will be generated and it will terminate the program. If we remove the checked context, the exception will not be thrown.

Checked: We enable a checked context with the checked keyword. This can be activated through the compiler option "/checked."

Num: The variable "num" is incremented to the value equal to one plus the int.MaxValue, which cannot fit in the memory location.

Increment

Then: The runtime uses special intermediate language instructions and generates an OverflowException.

OverflowException

Warning: The variable "num" will not contain a logically correct value in the unchecked context.

C# program that uses checked overflow context class Program { static void Main() { // // Use checked overflow context. // checked { // Increment up to max. int num = 0; for (int i = 0; i < int.MaxValue; i++) { num++; } // Increment up to max again (error). for (int i = 0; i < int.MaxValue; i++) { num++; } } } } Output Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at Program.Main()...
Unchecked example. Numeric types cause no exceptions when they overflow. This is the default behavior. It is also specified with the unchecked keyword.

Tip: This feature specifies that overflow is an acceptable result of an operation such as increment—no exception is thrown.

Example: The program uses the short type, which cannot exceed the value 32767. The program increments the short and causes overflow.

short, ushort

Note: In a checked context, an increment when the value is 32767 will throw an exception.

But: In an unchecked context, an increment will cause an overflow. The value will become invalid for most programs.

C# program that uses unchecked context using System; class Program { static void Main() { // The first short will overflow after the second short does. short a = 0; short b = 100; try { // // Keep incrementing the shorts until an exception is thrown. // ... This is terrible program design. // while (true) { checked { a++; } unchecked { b++; } } } catch { // Display the value of the shorts when overflow exception occurs. Console.WriteLine(a); Console.WriteLine(b); } } } Output 32767 -32669
Instructions. The execution engine includes support for the "ovf" suffix on arithmetical operations. This suffix indicates that the execution engine should check for overflow.

Note: In the program shown, the "add.ovf" instruction is used instead of the simple "add" instruction.

Warning: The checked context will impose a substantial performance penalty if an overflow is detected.

IL
A discussion. If the results of a computation are critical and there is a possibility the number ranges encountered will be large, using the checked context can easily inform you of errors.

And: This could prevent certain catastrophic errors related to large values becoming corrupted due to truncation.

Useful. The checked context is more often useful than the unchecked context. This is because the unchecked context is the default when compiling C# programs in the Microsoft compiler.

Tip: You do not need to specify unchecked unless you have specified an enclosing checked context.

Tip 2: It is a good idea to use unchecked explicitly in cases where you are also using checked. This provides more symmetry.

A summary. The checked keyword affects integer manipulations. It changes the behavior of the execution engine on certain arithmetical instructions. Unchecked eliminates these checks.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls