Short circuit on |= and &= assignment operators in C#

后端 未结 3 1463
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 10:09

I know that || and && are defined as short-circuit operators in C#, and such behaviour is guaranteed by the language specification, but do

3条回答
  •  时光取名叫无心
    2020-11-30 10:17

    No, the &= and |= operators are not doing short-circuit evaluation.

    They are pseudo-operators, which the compiler converts into use of the & and | operators.

    This code:

    allEven &= IsEven(numbers[i]);
    

    is exactly equivalent to:

    allEven = allEven & IsEven(numbers[i]);
    

    If you want the short circuited check, then you have to write it out using the short circuiting versions of the operators:

    allEven = allEven && IsEven(numbers[i]);
    

    There is no &&= pseudo operator, but the code above is exactly what the compiler would do if there was one.

提交回复
热议问题