Enable overflow checking in C# projects in debug mode only
Added: 10/16/2023 8:00 PM
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: <PropertyGroup> <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> </PropertyGroup> 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'"> <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> </PropertyGroup>