Knowledge - Details

Enable overflow checking in C# projects in debug mode only
Date Added: 10/17/2023

By default C# projects do not check for arithmetic overflow/underflow exceptions with integer operations.  It just silently ignores them and returns a wrong value.  An overflow is unlikely to occur unless your program may encounter very large numbers, and enabling overflow checking would slightly decrease application performance.  But enabling it would eliminate the possibility of an overflow/underflow bug going unnoticed and causing more damage.

Demonstration Code:
// by default, this will happily write an invalid value to "b" without any exception being thrown.  But, enabling CheckForOverflowUnderflow would cause this code to throw an exception instead.
int a = Int32.MaxValue;
int b = a + 5;

To fix the issue, add this to your project file:

Or, to fix the issue only in Debug builds, to preserve maximum performance in Release builds, add this to your project file:
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">

Back to List

Disclaimer: Everything on this website is written for my own use. I disclaim any guarantees that the procedures and advice listed here are accurate, safe, or beneficial for anyone else. If you attempt to follow any procedures or advice shared here, you do it at your own risk. Part of IT work is knowing how to recover from problems.