Checking for Overflow

Learn about handling in C#, covering the checked and unchecked statements to disable compile-time overflow checks.

Earlier, we saw that when casting between number types, it was possible to lose information, for example, when casting from a long variable to an int variable. If the value stored in a type is too big, it will overflow.

Throwing overflow exceptions with the checked statement

The checked statement tells .NET to throw an exception when an overflow happens instead of allowing it to happen silently, which is done by default for performance reasons. We will set the initial value of an int variable to its maximum value minus one. Then, we will increment it several times, outputting its value each time. Once it reaches its maximum value, it overflows to its minimum value and continues incrementing. Let’s see this in action:

Step 1: Use your preferred coding tool to add a new Console App/console named CheckingForOverflow to the Chapter03 workspace/solution.

  • In Visual Studio Code, select CheckingForOverflow as the active OmniSharp project.

Step 2: In Program.cs, delete the existing statements, and then type statements to declare and assign an integer to one less than its maximum possible value, and then increment it and write its value to the console three times, as shown in the following code:

Get hands-on with 1400+ tech skills courses.