Ok, here are some things I don't understand. I have defined variables:

byte b = 0x10; const byte a = 0x08;

When I try

b = b & a

it says "Cannot implicitly convert int to byte." How can byte & byte be an int??


Second thing. I have following:

b = (byte)(b & ~a);

Compiler has no problem with that. BUT if I use

b &= (byte) ~a;

it says "Constant value -9 cannot be converted to byte."
What's the difference between those two notations?

Thanks for your answers.

It seems that the compiler returns an integer as a bitwise operation.

I found nothing stating that the return value should be an integer, but all the examples I found are integer based :(

Also I found that I never used bitwise operations on other types than integer.

Sincerely.

For b &= (byte) ~a; , the compiler will check this conversion since a is a constant, and it is certain what the value will be. Since bitwise operations return int's (doesn't seem right to me), it will evaluate ~a as an int, which would evaluate to -9. I don't think there is any other way, except to use unchecked statements:

unchecked
{
    b &= (byte) ~a;
}

I know this is closed already, but it says in the C# standard "Bitwise operators are predefined for int, uint, long, and ulong", and this is why the byte is cast into an Int32.

This question has already been answered. Start a new discussion instead.