Reputation: 25983
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?
Upvotes: 6
Views: 3224
Reputation: 189457
Because byte (and short) types do not implement those operators
See Spec: 4.1.5
Upvotes: 0
Reputation: 1500585
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);
Upvotes: 12