3

I have this simple piece of code in C# to show overflow error when adding 1 to MaxValue of types.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte a = byte.MaxValue;
            byte b = 1;
            Console.WriteLine("Max+1 is : {0}", a+b);

            Console.ReadLine();
        }
    }
}

But instead of overflow and a wrong result, it generates correct value: 256 Why? While maximum value of byte variable in C# is 255. Am I wrong?

  • why should `string str = (255 + 1).ToString();` throw an error? – SᴇM Feb 26 '19 at 05:57
  • 1
    Adding `byte c = a + b;` seems to get to the bottom of how the addition is done: _"Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)"_ - it seems that `byte` is implicitly cast to an `int` for this addition. – ProgrammingLlama Feb 26 '19 at 05:58
  • 1
    You're just adding those two values and displaying them, you're not assigning them to a byte. – devsmn Feb 26 '19 at 05:59
  • 2
    When you add bytes they are implicitly cast to ints. Check out https://stackoverflow.com/questions/941584/byte-byte-int-why – Jerry Feb 26 '19 at 06:00

1 Answers1

3

Addition on anything less than a int is done in int. This is described in the Standard ECMA-334 C# specification under Numeric promotions

12.4.7 Numeric promotions

When overload resolution rules (§12.6.4) are applied to this set of operators, the effect is to select the first of the operators for which implicit conversions exist from the operand types. [Example: For the operation b * s, where b is a byte and s is a short, overload resolution selects operator *(int, int) as the best operator. Thus, the effect is that b and s are converted to int, and the type of the result is int. Likewise, for the operation i * d, where i is an int and d is a double, overload resolution selects operator *(double, double) as the best operator. end example]

Additionally, if you want to catch overflows you will need to use the checked keyword

Example

byte a = byte.MaxValue;
byte b = 1;
byte c = checked((byte)(a + b));

Additional Resources

checked (C# Reference)

By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow. Evaluating the expression assigned to i2 in the following example does not cause a compiler error.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141