I've noticed something odd about using the bitwise XOR operator on byte
s 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:
if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.
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.
In most C-like languages, operators will promote types smaller than int
to int
.
In such languages, a op= b
is equivalent to a = (typeof a)(a op b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With