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.

Add a new console application project named Ch03_CheckingForOverflow.

The checked statement

The checked statement tells .NET to throw an exception when an overflow happens instead of allowing it to 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 it gets above its maximum value, it overflows to its minimum value and continues incrementing from there.

Type the following code in the Main ...

Get C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.