Adding bytes in C#

Akos Nagy
Nov 20, 2017

What happens if you run this little piece of code? More specifically, what's the type of the variable 'x'?

byte b1=1;
byte b2=1;
var x=b1+b2;

Well, if you guessed byte, you were wrong. This will actually result in an int. This was brought to my attention by one of my students. So I dug a little deeper.

Why is this so? Well, first I went to check out the source of System.Byte. And to my surprise, there was no + operator! This means that when two bytes are added, the + operator of another type is called. This must be a type to which byte can be implicitly converted. If there is more (there is), we have to choose the 'best'. And the best is System.Int32.

So that's what happens: the two bytes are first implicitly converted to int, and then the addition operator of the int is called, which, in turn, returns an int.

As to why is this so, I have no idea. I went to Stackoverlow and found a question about this with a comment from Eric Lippert. I'm not entirely convinced, though...

Akos Nagy
Posted in C# .NET Teaching