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?
Various operators aren’t declared for
byte– both operands get promoted toint, and the result isint. For example, addition:Note that compound assignments do work:
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: