No overflow exception for int in C#?

erikric picture erikric · Jan 13, 2010 · Viewed 39.9k times · Source

I had this weird experience with problem number 10 on Project Euler (great site by the way). The assignment was to calculate the sum of all the prime numbers below two million.

I used an int for the sum, and my algorith produced an answer, but when i pasted it to verify the answer, it was wrong.

It turned out that the result was too big to fit in an int, but wouldn't this cause an overflow error or something? Instead, it just returned a value far off from the real answer.

When I changed the type to long, everything was hunky dory.

Answer

Konrad Rudolph picture Konrad Rudolph · Jan 13, 2010

C# integer operations don’t throw exceptions upon overflow by default. You can achieve that via the project settings, or by making the calculation checked:

int result = checked(largeInt + otherLargeInt);

Now the operation will throw.

The opposite is unchecked, which makes any operation explicitly unchecked. Obviously, this only makes sense when you’ve got checked operations enabled in the project settings.