This is a bit of a “soft question”, but basically I’m trying to take this pattern that makes use of implicit conversion to byte:
byte x = 0;
x |= 2; // implicit conversion of "x | 2" to byte here
and use it for removing bits:
x &= ~2; // compile error
The shortest that I could come up with is this:
x &= unchecked((byte) ~2);
(at which point I start seriously considering just writing x &= 253; // ~2 instead… or just the good old explicit cast: x = (byte) (x & ~2);)
Am I missing a shorter way?
How about this:
Explanation: There are two issues here. First, the unary operator ‘~’:
From C# Spec 4.1.5:
Once you apply the unary operator, the result is always, at the smallest, an ‘int’ type. From there, you want to implicitly convert to a byte.
Secondly, Implicit conversions:
So, ~2, is always an int. It cannot be converted to byte implicitly, because its outside of the range. You can convert implicitly if you constrain it to be within the range.