Search code examples
c#boolean-operations

&&= in C#? (boolean expression)


Possible Duplicate:
Why are there no ||= or &&= operators?

By pure accident I found out today that

 a &= GetBool();

is NOT the same as

 a = a && GetBool();

I must have misunderstood that for years. In the first Example, "GetBool()" is executed even if "a" is false. In the second, it isn't.

Is there anything to achieve something like "&&=" in C#?


Solution

  • From the documentation:

    An expression using the &= assignment operator, such as

    x &= y

    is equivalent to

    x = x & y

    except that x is only evaluated once. The & operator performs a bitwise logical AND operation on integral operands and logical AND on bool operands.

    I would say, to avoid evaluation of y when not necessary, use

    x = x && y
    

    and to avoid evaluation of x twice (whatever this means), use

    x &= y
    

    You can't combine both.

    Micro-optimized (at least for a theoretical case), it would be:

    if (x) x = y;
    

    You don't need to do anything if x is already false.