The checked keyword is used to control the overflow-checking context for integral-type arithmetic operations and conversions. It can be used as an operator or a statement according to the following forms.
The checked statement:
checked block
The checked operator:
checked (expression)
where:
In a checked context, if an expression produces a value that is outside the range of the destination type, the result depends on whether the expression is constant or non-constant. Constant expressions cause compile time errors, while non-constant expressions are evaluated at run time and raise exceptions.
If neither checked nor unchecked is used, a constant expression uses the default overflow checking at compile time, which is checked. Otherwise, if the expression is non-constant, the run-time overflow checking depends on other factors such as compiler options and environment configuration.
The following three examples demonstrate the checked and unchecked operators on non-constant expressions. All use the same algorithm, but different checking contexts. The overflow checking is evaluated at run time.
Only the first example throws an overflow exception at run time, in which case, you have the option to go to the debugging mode, or abort the program execution. The other two examples produce truncated values.
See also the unchecked examples on using the checked and unchecked statements.
// Using checked expressions // The overflow of non-constant expressions is checked at run time using System; class OverFlowTest { static short x = 32767; // Max short value static short y = 32767; // Using a checked expression public static int myMethodCh() { int z = checked((short)(x + y)); return z; // Throws the exception OverflowException } public static void Main() { Console.WriteLine("Checked output value is: {0}", myMethodCh()); } }
When you run the program, it throws the exception OverflowException
. You can debug the program or abort execution.
// Using unchecked expressions // The overflow of non-constant expressions is checked at run time using System; class OverFlowTest { static short x = 32767; // Max short value static short y = 32767; public static int myMethodUnch() { int z = unchecked((short)(x + y)); return z; // Returns -2 } public static void Main() { Console.WriteLine("Unchecked value is: {0}", myMethodUnch()); } }
Unchecked value is: -2
// Using default overflow checking // The overflow of non-constant expressions is checked at run time using System; class OverFlowTest { static short x = 32767; // Max short value static short y = 32767; public static int myMethodUnch() { int z = (short)(x + y); return z; // Returns -2 } public static void Main() { Console.WriteLine("Default checking ouput value is: {0}", myMethodUnch()); } }
Default checking ouput value is: -2