Y U No Overflow?!

A team member and I were recently interviewing candidates for a new developer position on our team.  In one of the interviews, a question took us down an unexpected but interesting path regarding overflow exceptions in .NET.  We were asking something along the lines of, what happens when you add two large 32-bit integers and the result exceeds the storage size allowed for an Int32?  Would this result in an OverflowException?  Well, it could however, this is not the default behavior in .NET.

Let’s take a look at the following code.

What happens when it is executed? Here is the output.

Numeric Value -  2147483647, Binary Value -  1111111111111111111111111111111
Numeric Value - -2147483648, Binary Value - 10000000000000000000000000000000

Wait a minute!? Y U No Overflow?! 

yuno

The answer lies with how .NET handles overflow checking.  Let’s take our previous example and modify it slightly by wrapping the incrementing of our variable in a checked block.

Now we see the exception that may have been previously expected.

System.OverflowException: Arithmetic operation resulted in an overflow.

Statements in C# will execute in either a checked or unchecked context.  The context can be changed in one of two ways.

  1. Using the checked keyword and placing code in a checked block
  2. Setting CheckForOverflowUnderflow build setting to true

It is also worth mentioning that an unchecked keyword also exists though it is seldom used.  With the default behavior being unchecked, the unchecked keyword is only has value when the CheckForOverflowUnderflow build setting is set or you are within a checked block.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s