Tuesday, December 28, 2010

C#: Checked and unchecked keywords

Today I came across two C# keywords that I haven't noticed before, checked and unchecked.

After some research it turns out that checked and unchecked are used to control the overflow checking of integral-type arithmetic operations and conversions. This means that by using checked, if a value is out of range for the destination type, depending on the complexity of the expression either a compile-time error will be given or a runtime exception of type System.OverflowException will be thrown. While if unchecked is used, the number will be truncated. Both of these keywords can either be used as block statements or as operators.

Unchecked example:


int i = unchecked(Int32.MaxValue);
// i is now 2147483647

int i = unchecked(Int32.MaxValue + 1);
// i is now -2147483648

Checked example:


int i = checked(Int32.MaxValue);
// i is now 2147483647

int i = checked(Int32.MaxValue + 1);
// Gives a compile-time error, "Error: The operation overflows at compile time in checked mode"

checked
{ 
 int i = Int32.MaxValue;
 i++;
}
// Throws a runtime exception, "System.OverflowException: Arithmetic operation resulted in an overflow".