Bitwise NOT on const byte fields in C #
I figured out that if I have a field or variable of type 'byte' I can apply a bitwise NOT (~) on it and pass it in byte. However, if the field is "const byte", I can still apply the bitwise NOT (~), but I cannot pass it in byte. For example,
This compiles:
class Program
{
byte b = 7;
void Method()
{
byte bb = (byte) ~b;
}
}
But this has a compilation error ("The constant value" -8 "cannot be converted to" byte "):
class Program
{
const byte b = 7;
void Method()
{
byte bb = (byte) ~b;
}
}
I wonder why?
source to share
Since the operator ~
is predefined only for int
, uint
, long
and ulong
. Your first example implicitly passes b
in int
, performs negation, then explicitly returns to byte.
In the second example, b
is a constant, so the compiler inserts negation as well, effectively making the constant int
value -8 (signed double's complement 7). And since a constant negative value cannot be appended to byte
(without adding context unchecked
), you will get a compilation error.
To avoid the error, just store the result in a non-constant variable int
:
const byte b = 7;
void Main()
{
int i = ~b;
byte bb = (byte)i;
}
source to share
For byte
no operator ~
. It is defined for int
. byte
is implicitly converted to int
, int
NOT-ed. The result is int
not in the range byte
(0 to 255 inclusive), so it can only be converted to at byte
compile time with an unchecked act:
byte bb = unchecked((byte)~b);
The second program does not compile because, due to the use of compile-time constants, it can check for incorrect conversions at compile-time. The compiler cannot make this assertion with non-compiled time constant values.
source to share