What is the best practice concerning C# short-circuit evaluation?

前端 未结 3 735
生来不讨喜
生来不讨喜 2020-12-15 21:31

An answer and subsequent debate in the comments in another thread prompted me to ask:

In C# || and && are the short-circuited versions of the logical operato

3条回答
  •  离开以前
    2020-12-15 22:07

    Use && and || when you only care about the result and want to know that result as soon as possible and none of your expressions have side effects that must occur even if the boolean condition is not met. That is to say, pretty much always.

    Use & and | when every expression must be evaluated (for example, if you have side effects from your expressions). But since you should never have side effects that your program depends on that must occur even if the boolean condition is not met, you should probably not be using & and |.

    For example, this would probably be exceptionally silly:

    if (false & somethingThatUpdatesTheDatabase()) { /* ... */ }
    

提交回复
热议问题