Checking for arithmetic overflow in C# .NET
April 1, 2015 2 Comments
As you know primitive numeric types in C# – and other modern programming languages – have maximum and minimum values that can be stored in memory. If you’re trying to store a larger number in the variable then you’ll get an overflow with unexpected results.
Let’s see an example with the “byte” type. It is actually not one of the primitive types, like int or long, but simply a keyword for an integral type to store the numbers 0-255. Why 255? 1 byte consists of 8 bits and 8 bits in the computer’s memory allows us to store 255 as the highest number. 255 in binary is all 1’s for all 8 bits:
11111111
What happens if we add 1 to that? On paper we can easily solve it by some basic binary maths:
11111111
+ 00000001
===========
100000000
That’s 1 followed by 8 zeroes which is 256 in the binary system. However, for a computer that’s not a possibility as it cannot just use one extra bit to store the leading 1. It will instead drop the 1 and have only 8 zeroes instead. Let’s check that:
byte a = 255; byte b = 1; byte res = (byte)(a + b);
Adding two byte values will be cast to an integer so we’ll need to cast it back to a byte. If you run this method then res will be 0 without raising an exception.
Let’s see another example with integers:
int first = int.MaxValue; int second = 10000; int result = first + second;
“result” will be -2147473649 which definitely smells. Again, the runtime didn’t complain.
The reason why it didn’t complain is that C# does not automatically check for overflows after arithmetic operations. That would add a lot of overhead to your code. There’s an easy way to carry out this check using the “checked” block:
checked { int result = first + second; }
Rerunning this bit of code will now raise an exception of type OverflowException.
So if you suspect that some calculation in your code produces seemingly random results then you might want to add the checked block to verify if there’s an overflow.
View all various C# language feature related posts here.
Reblogged this on Brian By Experience.
Reblogged this on Dinesh Ram Kali..