Control overflow behavior with checked and unchecked in C#

example

C# handles overflow with different data types differently. You can control this to some extent with the checked and unchecked keywords.

If you execute code inside a checked block and an int or long operation causes an overflow, the block throws an exception.

If you execute code inside an unchecked block (or no block–this is the default behavior) and an int or long operation causes an overflow, the value simply overflows and creates a gibberish value without giving you any indication that there is a problem.

The following code uses longs to try to calculate the factorial function. If there is an overflow, the checked block throws an exception.

private string LongFactorial(long N)
{
    // Long obeys checked and unchecked.
    try
    {
        checked
        {
            long result = 1;
            for (long i = 2; i <= N; i++) result *= i;
            return result.ToString();
        }
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

Try changing this to an unchecked block or try removing the checked block to see what happens.

The float and double data types ignore checked and return Infinity if there’s overflow.

The decimal type ignores unchecked and always throws an exception if there’s overflow.

Nice and consistent, huh?

The following table summarizes how the data types behave.

Data Type Default Checked Unchecked
int Gibberish Exception Gibberish
long Gibberish Exception Gibberish
decimal Exception Exception Exception
float Infinity Infinity Infinity
double Infinity Infinity Infinity

The moral is to be aware of the kinds of failures a data type might produce. Unless you really don’t care, use checked to catch exceptions with ints and longs, always catch exceptions with decimals, and look for Infinity with floats and doubles.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in calculations, mathematics, syntax and tagged , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Control overflow behavior with checked and unchecked in C#

  1. Pingback: See how much time a checked block takes in C# -

Leave a Reply

Your email address will not be published. Required fields are marked *