John Woo
John Woo

Reputation: 263733

byte + byte = unknown result

Good day SO! I was trying to add two byte variables and noticed weird result.

byte valueA = 255;
byte valueB = 1;
byte valueC = (byte)(valueA + valueB);

Console.WriteLine("{0} + {1} = {2}", valueA.ToString(), 
                                     valueB.ToString(), 
                                     valueC.ToString());

when i tried to run the program, It displays

255 + 1 = 0

What happened to the above code? Why doesn't the compiler throws an OverflowException? How can I possibly catch the exception? I'm a VB guy and slowly migrating to C# :) Sorry for the question.

Upvotes: 12

Views: 413

Answers (2)

SkyDrive
SkyDrive

Reputation: 1455

because by default, C# doesn't check for arithmetic operation overflows. try wrapping it with checked so it will throw exception.

try this:

byte valueA = 255;
byte valueB = 1;
byte valueC = (byte)(valueA + valueB);

Console.WriteLine("Without CHECKED: {0} + {1} = {2}", valueA.ToString(), 
                                                      valueB.ToString(), 
                                                      valueC.ToString());

try
{
    valueC = checked((byte)(valueA + valueB));
    Console.WriteLine("With CHECKED: {0} + {1} = {2}", valueA.ToString(), 
                                                       valueB.ToString(), 
                                                       valueC.ToString());
}
catch (Exception e)
{
    Console.WriteLine("With CHECKED: " + e.GetType());
}

checked @ MSDN

Upvotes: 9

SLaks
SLaks

Reputation: 887459

C# code is unchecked by default, so that overflows will silently wrap around rather than throwing an exception.

You can get an exception by wrapping your code in a checked block, at the cost of a slight performance hist.

Upvotes: 17

Related Questions