Checking for overflow
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 gets above its maximum value, it overflows to its minimum value and continues incrementing from there.
Let's see this in action:
- In
Program.cs
, 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:
int x = int.MaxValue...