Antoine C.
Antoine C.

Reputation: 3962

Use of bitwise operator in condition - Cannot implicitly convert type `int' to `bool'

I wrote the following code that uses a bitField variable as a map for characters to check their presence in a given string:

public static bool AllElementsUniqueInASCIIString(string str) {
    int bitField = 0;
    
    foreach (int character in str) {
        int idx = character - 'a';
        int mask = 1 << idx;
        if (bitField | mask == 1)
            return false;
        else
            bitField &= mask;
    }
    
    return true;
}

The problem is, on the expression if (bitField | mask == 1), the following error is thrown at compile time:

CS0029: Cannot implicitly convert type 'int' to 'bool'

However, when I replace this line with the following snippet, the code compiles just fine:

   int present = bitField | mask;
   if (present == 1) 

Both bitField and mask are integer, so what is the matter of this compile error? What syntax should I use to check this condition in one line?

Upvotes: 1

Views: 459

Answers (1)

TheGeneral
TheGeneral

Reputation: 81573

You will need brackets to explicitly express your intentions

if ((bitField | mask) == 1)

The compiler thinks you are wanting to do the following (due to operator precedence)

if (bitField | (mask == 1))
      int    |    bool

Which is what the error is telling you

CS0019 Operator '|' cannot be applied to operands of type 'int' and 'bool'

In short, equality operators have precedence over Boolean logical OR or bitwise logical OR operators


Additional Resources

Operator precedence

In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence

Upvotes: 4

Related Questions