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
uncheckedby default, so that overflows will silently wrap around rather than throwing an exception.You can get an exception by wrapping your code in a
checkedblock, at the cost of a slight performance hist.