Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte + byte = unknown result

Tags:

c#

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.

like image 608
John Woo Avatar asked Jul 22 '12 14:07

John Woo


2 Answers

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.

like image 150
SLaks Avatar answered Oct 30 '22 17:10

SLaks


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

like image 34
SkyDrive Avatar answered Oct 30 '22 15:10

SkyDrive