Checking for Overflow
Explore how to identify and manage numeric overflow in C# by using checked statements to throw exceptions when overflow occurs and unchecked statements to disable compile-time overflow checks. Understand how to implement these concepts in your code to improve error handling and avoid silent data loss.
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 ...