Arithmetic Operations with Small Integers

When doing arithmetic operations on variables of type bytesbyteshort or ushort, the data values are first converted to int and the operations are performed on int types.
As an example, note that the following code does not compile.  You receive the compiler error “Cannot implicitly convert type ‘int’ to ‘byte’“.
1
2
3
byte b1 = 5;
byte b2 = 6;
byte b3 = b1 + b2;
The problem is that the “b1 + b2″ expression is evaluated as an int.  The two byte variables are first converted to int and the sum is calculated as an int.  But then we try to assign this int result back to a byte.  Because byte is smaller thanint, we can’t do an implicit cast from int to byte.
We can avoid the compilation error by doing an explicit cast:


1
2
3
byte b1 = 5;
byte b2 = 6;
byte b3 = (byte)(b1 + b2);