This is a mirror of official site: http://jasper-net.blogspot.com/

C# Snippet Tutorial - The checked and unchecked keywords

| Thursday, March 25, 2010
Every once and a while I run across a new C# keyword that I've never used before. Today it's checked  and unchecked. Basically, these keywords control whether or not an exception will be thrown when an operation causes a number to overflow.

First, let's check out unchecked. The unchecked keyword will prevent exceptions from being thrown if a number overflows. By default, .NET does not throw exceptions for overflows, which means the following use of unchecked has no affect. What the unchecked keyword can do, however, is prevent compilation errors if the value can be calculated at compile-time. If you attempt to set an integer equal to 2147483647 + 1, the compiler will throw an error since it knows that value won't fit in an int.

// With an unchecked block, which is the
// default behavior, numbers will roll-over.
unchecked
{

int i = int.MaxValue;
Console.WriteLine(i); //2147483647
i++;
Console.WriteLine(i); //-2147483648
}

As you can see, I initialize an integer to its max value, then increment it by one. The value then rolls over to a negative number and no exception is thrown. If we switch the block to a checked block, we'll now get an exception.

Read more: Switch on code

Posted via email from jasper22's posterous

0 comments: