Thursday, January 29, 2009

Using the checked context in C#

In C# you can place an assignment in a checked context to force an exception at runtime if the value being assigned is outside the range of the data type being assigned to.

void foo(int m) // assume that m is +2,147,483,647 (i.e. max value for an usigned Int32)
{
   int j = m * 4; // will not throw an exception but value in j will be truncated
   checked
   {
      int i = m * 4; // will throw an exception because it's in a checked context
   }
}

This assumes that you're using the C# compiler's default option which is /checked-. If you had set the compiler's /checked+ option then the first assignment to j would have also caused an exception at runtime in the example above. In a checked context, arithmetic overflow raises an exception.

However, if you attempt to assign a value that's tool large for a data type which is known at compile time this will cause a compiler error. For example:

const int x = 2147483647;   // Max int 
const int y = 2;
int z = x * y;

will cause the compiler to generate the following error: "The operation overflows at compile time in checked mode"
 
To prevent this and allow trucation during the assignment to z you should wrap the assignment to z in an unchecked context.
 
 

No comments:

Post a Comment