Re: Unexpected integer addition result

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Joakim Karlsson (jkarlsson_at_NOSPAMjkarlsson.com)
Date: 01/06/05


Date: Thu, 06 Jan 2005 21:44:55 +0100

Henning Krause [MVP] wrote:
> I think this setting is unchecked by default because of of performance
> considerations.

I think that is a reasonable default setting. Most operations in your
code probably do not need overflow checking. Perhaps it should be on by
default in debug builds though.

If you have code where you do need to consider overflows, wrap that in a
checked statement.

Beware though that the checked statement is not able to span over method
calls.

This will not work:

public static void Main()
{
   checked
   {
     Console.WriteLine (ShortTest());
     Console.WriteLine (IntTest());
     Console.WriteLine (LongTest());
   }
}

You will have to add the check inside the methods where an overflow may
arise:

public static int IntTest()
{
   checked
   {
     int _l1;
     _l1 = (int.MaxValue - 20);
     return _l1 + 1000;
   }
}

/Joakim