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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With