I just discovered that C# will not let you perform bitwise operations on a ulong and an int. Every other combination of int, uint, long, and ulong will work, but that one pairing doesn't.
However, if instead of an int, I have a const int, everything is fine.
What's going on here? Why is int & ulong invalid, but const int & ulong valid?
Broken:
int mask = 0x1110;
ulong value = 0x1010;
var result = mask & value; // Compilation error: "Operator '&' cannot be applied to operands of type 'int' and 'ulong'"
Working:
const int mask = 0x1110;
ulong value = 0x1010;
var result = mask & value; // Works just fine.
This behavior is not specific to bitwise operations. According to C# Language Specification, it applies to all binary operations requiring numeric promotions.
Section 7.6.3.2 describes binary numeric promotions. I emphasized the section that specifies the behavior that you see:
The reason the problem does not happen when you use
constis that the compiler is allowed to convertconst intexpression to other types, as described in section 7.19:Since the value of
mask, i.e.0x1110, fits withinulong, the compiler performs the promotion instead of triggering the error.