C# Snippet Tutorial - The checked and unchecked keywords [Beginner]


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.
// With a checked block, an exception
// will be thrown if an operation on a
// number will cause a roll-over.
checked
{
  int i = int.MaxValue;
  Console.WriteLine(i); //2147483647


  try
  {
    i++;
  }
  catch (System.OverflowException ex)
  {
    Console.WriteLine(ex);
  }

  Console.WriteLine(i); //2147483647
}
 
With this code, when I attempt to increment the integer, a System.OverflowException is thrown. Using the checked keyword (or compiler option) is a great way to catch number overflows during development and testing, since it's very rare that I actually want an overflow to occur during production code.

Comments