I’ve noticed something odd about using the bitwise XOR operator on bytes in C#. Odd to my mind, at least.
byte a = 0x11;
byte b = 0xAA;
a ^= b; // works
a = a ^ b; // compiler error: Cannot implicitly convert type "int" to "byte"
I also see this issue using short, but not int or long.
I thought the last two lines were equivalent, but that doesn’t seem to be the case. What’s going on here?
There is no xor operator that takes and returns bytes. So C# implicitly widens the input bytes to ints. However, it does not implicitly narrow the result int. Thus, you get the given error on the second line. However, §14.14.2 (compound assignment) of the standard provides that:
x and y (the inputs) are both bytes. You can explicitly narrow a int to a byte, and clearly a byte is implicitly convertible to a byte. Thus, there is an implicit cast.