Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XOR operators: ^ vs ^= and implicit type conversion

Tags:

c#

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?

like image 661
Odrade Avatar asked Jul 29 '10 20:07

Odrade


2 Answers

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.

like image 113
Matthew Flaschen Avatar answered Oct 01 '22 10:10

Matthew Flaschen


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)

like image 21
Daniel Avatar answered Oct 01 '22 08:10

Daniel