Why does the following raise a compile time error: ‘Cannot implicitly convert type ‘int’ to ‘byte’:
byte a = 25;
byte b = 60;
byte c = a ^ b;
This would make sense if I were using an arithmentic operator because the result of a + b could be larger than can be stored in a single byte.
However applying this to the XOR operator is pointless. XOR here it a bitwise operation that can never overflow a byte.
using a cast around both operands works:
byte c = (byte)(a ^ b);
I can’t give you the rationale, but I can tell why the compiler has that behavior from the stand point of the rules the compiler has to follow (which might not really be what you’re interesting in knowing).
From an old copy of the C# spec (I should probably download a newer version), emphasis added:
So, basically operands smaller than an
intwill be converted tointfor these operators (and the result will be anintfor the non-relational ops).I said that I couldn’t give you a rationale; however, I will make a guess at one – I think that the designers of C# wanted to make sure that operations that might lose information if narrowed would need to have that narrowing operation made explicit by the programmer in the form of a cast. For example:
While this kind of truncation wouldn’t happen when performing an xor operation between two byte operands, I think that the language designers probably didn’t want to have a more complex set of rules where some operations would need explicit casts and other not.
Just a small note: the above quote is ‘informational’ not ‘normative’, but it covers all the cases in an easy to read form. Strictly speaking (in a normative sense), the reason the
^operator behaves this way is because the closest overload for that operator when dealing withbyteoperands is (from 14.10.1 “Integer logical operators”):Therefore, as the informative text explains, the operands are promoted to
intand anintresult is produced.