Checking for arithmetic overflow in C# .NET

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Checking for arithmetic overflow in C# .NET

  1. Pingback: Checking for arithmetic overflow in C# .NET | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: