ProAnswers.org

why not byte + byte = byte in C#?

Looking at this C# code…

byte x = 1;     byte y = 2;     byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte' The result of any math performed on byte (or short) types is implicitly cast back to an integer. The solution is to explicitly cast the result back to a byte, so...

byte z = (byte)(x + y);   // works What I am wondering is why? Is it architectural? Philosophical? 

We have:

•int + int = int
•long + long = long
•float + float = float
•double + double = double
So why not:

•byte + byte = byte
•short + short = short ?

I believe it’s basically for the sake of performance. (In terms of “why it happens at all” it’s because there aren’t any operators defined by C# for arithmetic with byte, sbyte, short or ushort, just as others have said. This answer is about why those operators aren’t defined.)

Processors have native operations to do arithmetic with 32 bits very quickly. Doing the conversion back from the result to a byte automatically could be done, but would result in performance penalties in the case where you don't actually want that behaviour.



I think this is mentioned in one of the annotated C# standards.

The third line of your code snippet:

byte z = x + y;

actually means

byte z = (int) x + (int) y;

So, there is no + operation on bytes, bytes are first cast to integers and the result of addition of two integers is a (32-bit) integer.