The unchecked 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 unchecked statement:
unchecked block
The unchecked operator:
unchecked (expression)
where:
In an unchecked context, if an expression produces a value that is outside the range of the destination type, the result is truncated.
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 are three examples demonstrating the checked and unchecked statements. All use the same algorithm, but different checking contexts. The three examples are using constant expressions, for which the overflow checking is evaluated at compile time.
Only the unchecked statement produces a truncated value. The other two statements produce compile-time errors.
See also the checked examples on using the checked and unchecked operators.
// Using the unchecked statement with constant expressions // Overflow is checked at compile time using System; class TestClass { const int x = 2147483647; // Max int const int y = 2; public int MethodUnCh() { // Unchecked statement: unchecked { int z = x * y; return z; } // Returns -2 } public static void Main() { TestClass myObject = new TestClass(); Console.WriteLine("Unchecked output value: {0}", myObject.MethodUnCh()); } }
Unchecked output value: -2
// Using default overflow checking with constant expressions // Overflow is checked at compile time using System; class TestClass { const int x = 2147483647; // Max int const int y = 2; public int MethodDef() { // Using default overflow checking: int z = x * y; return z; // Compiler error } public static void Main() { TestClass myObject = new TestClass(); Console.WriteLine("Default checking value: {0}", myObject.MethodDef()); } }
The compilation error: The operation overflows at compile time in checked mode.
// Using the checked statement with constant expressions // Overflow is checked at compile time using System; class TestClass { const int x = 2147483647; // Max int const int y = 2; public int MethodCh() { // Checked statement: checked { int z = (x * y); return z; } // Compiler error } public static void Main() { TestClass myObject = new TestClass(); Console.WriteLine("Checked value: {0}", myObject.MethodCh()); } }
The compilation error: The operation overflows at compile time in checked mode.