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 ...