1
byte num1 = 5;
byte num2 = 6;

byte res = num1 + num2; 
//Adding bytes asks for a explicit cast to int - "Cannot Implicitly Convert 'int' to 'byte'

This can be justified by assuming the case that what if the arithmetic operation causes an overflow. So if this is going to be the case then what for int?

int num1 = 2;
int num2 = 4;

int res = num1 + num2;
// This works, but when we take the previous assumption to consideration here
// here int may also lead to overflow right 

So this should also throw a cast error right, it should ask for long and the chain continues right?

There already another stackoverflow question similar to this but it is not answering this question. byte + byte = int... why?

Raghav venkat
  • 170
  • 2
  • 15
  • `byte` + `byte` = `int` is not because "there might be overflow". It's because there are only 4 `+` operators defined. See the list [here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#addition-operator). – Sweeper Jul 09 '20 at 04:37
  • Also, even if overflow could be a justification for the type promotion, the byte + byte result would be `short`, not `int`, so I don't really see it as a valid justification. – itsme86 Jul 10 '20 at 20:43

1 Answers1

4

Just because it "can be justified" that way, doesn't mean that that is the reason.

Eric Lippert, who would know, was clear about this in a comment on the question you linked:

The various musings below are a reasonable approximation of the design considerations. More generally: I don't think of bytes as "numbers"; I think of them as patterns of bits that could be interpreted as numbers, or characters, or colors or whatever. If you're going to be doing math on them and treating them as numbers, then it makes sense to move the result into a data type that is more commonly interpreted as a number.

Patrick Stevens
  • 569
  • 3
  • 17
  • Makes sense! I din't notice that Thanks! – Raghav venkat Jul 09 '20 at 04:42
  • In C the definition of `int` doesn't actually specify the size. It's allowed to map to a type the CPU can efficiently use. – Jeremy Lakeman Jul 09 '20 at 04:50
  • @JeremyLakeman I don't think that's relevant; the question is about C#. – Patrick Stevens Jul 09 '20 at 05:34
  • I'm sure that C's implicit type promotions for '+', influenced the design of C#'s. – Jeremy Lakeman Jul 09 '20 at 05:44
  • 2
    @Raghavvenkat: I also addressed the specific question in the comments to https://stackoverflow.com/a/4347752/88656. Briefly: if int plus int is long then that is essentially saying *every integer math computation in C# is to be done in longs*, because why would you stop at addition? Multiplication then also needs to be in longs, and if addition and multiplication of ints makes a long then so does subtraction and division, and now we're doing all arithmetic in 64 bits all the time. That has performance implications, and it has code readability implications. – Eric Lippert Jul 09 '20 at 20:23