Bitwise operations, ulong and int

I just discovered that C # will not allow you to perform bitwise operations on ulong and int . Any other combination of int , uint , long and ulong will work, but this one pairing does not work.

However, if instead of int , I have const int , everything is fine.

What's going on here? Why is int & ulong valid but const int & ulong valid?


Brocken:

 int mask = 0x1110; ulong value = 0x1010; var result = mask & value; // Compilation error: "Operator '&' cannot be applied to operands of type 'int' and 'ulong'" 

IN:

 const int mask = 0x1110; ulong value = 0x1010; var result = mask & value; // Works just fine. 
+7
c # bitwise-operators
source share
1 answer

This behavior does not apply to bitwise operations. According to the C # language specification, it applies to all binary operations requiring numerical promotions.

Section 7.6.3.2 describes binary numeric promotions. I emphasized the section that indicates the behavior you see:

Binary numeric promotion consists of applying the following rules in the following order:

  • If either operand is of type decimal , the other operand is converted to type decimal or a binding time error occurs if the other operand is of type float or double .
  • Otherwise, if either operand is of type double , the other operand is converted to type double .
  • Otherwise, if either operand is of type float , the other operand is converted to type float .
  • Otherwise, if either operand is of type ulong , the other operand is converted to type ulong or a binding time error occurs if the other operand is of type sbyte , short , int or long .
  • Otherwise, if either operand is of type long , the other operand is converted to type long .
  • Otherwise, if either operand is of type uint and the other operand is of type sbyte , short or int, both operands are converted to type long .
  • Otherwise, if either operand is of type uint , the other operand is converted to type uint .
  • Otherwise, both operands are converted to type int .

The reason the problem does not occur when using const is because the compiler is allowed to convert the const int expression to other types, as described in section 7.19:

The implicit conversion of constant expressions (ยง6.1.9) allows you to convert a constant expression of type int to sbyte , byte , short , ushort , uint or ulong if the value of the constant expression is within the target type.

Since the value of mask , i.e. 0x1110 , placed in ulong , the compiler performs the promotion instead of launching an error.

+9
source share

All Articles