Difference between eager operation and short-circuit operation? (| versus || and & versus &&)

后端 未结 7 1964
Happy的楠姐
Happy的楠姐 2020-11-30 15:55

I am (still) learning C# - and I thought I understood the difference between & & && as well as | & ||

相关标签:
7条回答
  • 2020-11-30 16:26

    & can be used in two different ways: bitwise "and" and logical "and"

    The difference between logical & and && is only that in case you use &, the second expression is also evaluated, even if the first expression was already false. This may (for example) be interesting if you want to initialize two variables in the loop:

    if ((first = (i == 7)) & (second = (j == 10))) { //do something }
    

    if you use this syntax, first and second will always have a value, if you use

    if ((first = (i == 7)) && (second = (j == 10))) { //do something }
    

    it may be that only first has a value after the evaluation.

    It is the same for | and ||: In case you use |, both of the expressions are always evaluated, if you use || it may be that only the first expression is evaluated, which would be the case if the first expression is true.

    In contrast, in other applications && can be the better choice. If myNumber is of type int?, you could have something like

    if (myNumber != null && myNumber.Value == 7)
    

    and this would only evaluate myNumber != null at first, and it would only evaluate the second expression, if the null check was okay.

    if (myNumber != null & myNumber.Value == 7)
    

    would finish with a NullPointerException during the evaluation of the second expression, if myNumber was null. Therefore, you would use && in this context.

    0 讨论(0)
提交回复
热议问题