Why can't I do boolean logic on bytes?

.net, boolean-logic, byte, c#

Solution

Various operators aren't declared for `byte` - both operands get promoted to `int`, and the result is `int`. For example, addition:

byte byte1 = 0x00;
byte byte2 = 0x00;
byte byte3 = byte1 + byte2; // Compilation error

Note that compound assignments do work:

byte1 += byte2;

There was a recent SO question on this. I agree this is particularly irksome for bitwise operations though, where the result should always be the same size, and it's a logically entirely valid operation.

As a workaround, you can just cast the result back to byte:

byte byte3 = (byte) (byte1 & byte2);

Problem

In C# (3.5) I try the following: ``` byte byte1 = 0x00; byte byte2 = 0x00; byte byte3 = byte1 & byte2; ``` and I get Error 132: "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)". The same happens with | and ^. What am I doing wrong? Why is it asking me about ints? Why can't I do boolean logic on bytes?

Original source

Related problems