-1

Let's say you have

class Program
{
    static void Main()
    {
        bool a = GetFalse();
        if (a)
        {
            a = GetTrue();
        }

        bool b = GetFalse();
        b &= GetTrue();
    }

    static bool GetFalse() => (false);

    static bool GetTrue() => (true);
}

Why will GetTrue() be executed when b is already false?

Shouldn't the &= operator recognize that it can never evaluate to true?

Dee J. Doena
  • 1,631
  • 3
  • 16
  • 26
  • No - the `&=` operator is equivalent to `x = x & y` and does not short-circuit. – D Stanley May 19 '16 at 15:17
  • 1
    A simpler explanation is that & is a bitwise operator, and to perform a bitwise operation you need the binary value of both operands, therefore you need to execute the second part even if the first is false. – zoubida13 May 19 '16 at 15:21
  • @zoubida13 `&`is only a bitwise operator on integral types - they are both boolean operators on boolean types. – D Stanley May 19 '16 at 15:26
  • @DStanley This is what I am [probably not so well] trying to say. To apply the bitwise operation (ie bit by bit) it needs to process both operands beforehand, and convert integral types if necessary. && is a logical operator in c#, not bitwise, it will take the boolean value of operand 1 and then decide to proceed with the boolean value of operand two. Although I admit we may be arguing on semantics here. – zoubida13 May 19 '16 at 15:30
  • It's not semantics. `&` is a non-short-circuiting _logical_ operator for boolean types. There is a common misconception that `&` is bitwise and `&&` is logical. They are _both_ logical for boolean types; the only difference is one short-circuits and one doesn't. – D Stanley May 19 '16 at 15:40

1 Answers1

5

Because x &= y is simply shorthand for x = x & y. & is not short-circuited, so y is evaluated regardless of the value of x, even for bools.

For bools, specifically, there is a short-circuited version of &: &&. There's no &&= operator, though, so you need to do it separately:

b = b && GetTrue();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875