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.
Add a new Console Application project named Ch03_CheckingForOverflow.
The checked
statement tells .NET to throw an exception when an overflow happens instead of allowing to it happen silently.
We set the initial value of an int
variable to its maximum value minus one. Then, we increment it several times, outputting its value each time. Note that once x
gets above its maximum value, it overflows to its minimum value and continues incrementing from there.
Type the following code in the Main
method and run the program:
int x = int.MaxValue - 1; WriteLine(x); x++; WriteLine(x); x++; WriteLine(x); x++; WriteLine(x);
Press Ctrl + F5 and view the output in the console:
2147483646 2147483647 -2147483648 -2147483647
Now let's get the compiler to...