C# XOR on two byte variables will not compile without a cast

Posted by Ash on Stack Overflow See other posts from Stack Overflow or by Ash
Published on 2010-04-28T04:57:09Z Indexed on 2010/04/28 5:03 UTC
Read the original article Hit count: 192

Filed under:
|

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);

© Stack Overflow or respective owner

Related posts about c#

Related posts about operators