Execution order of conditions in C# If statement

后端 未结 8 1919
孤城傲影
孤城傲影 2020-12-08 19:32

There are two if statements below that have multiple conditions using logical operators. Logically both are same but the order of check differs. The first one works and the

相关标签:
8条回答
  • 2020-12-08 20:13

    The conditions are checked left to right. The && operator will only evaluate the right condition if the left condition is true.

    Section 5.3.3.24 of the C# Language Specification states:

    5.3.3.24 && expressions

    For an expression expr of the form expr-first && expr-second:

    · The definite assignment state of v before expr-first is the same as the definite assignment state of v before expr.

    · The definite assignment state of v before expr-second is definitely assigned if the state of v after expr-first is either definitely assigned or “definitely assigned after true expression”. Otherwise, it is not definitely assigned.

    · The definite assignment state of v after expr is determined by:

    o If the state of v after expr-first is definitely assigned, then the state of v after expr is definitely assigned.

    o Otherwise, if the state of v after expr-second is definitely assigned, and the state of v after expr-first is “definitely assigned after false expression”, then the state of v after expr is definitely assigned.

    o Otherwise, if the state of v after expr-second is definitely assigned or “definitely assigned after true expression”, then the state of v after expr is “definitely assigned after true expression”.

    o Otherwise, if the state of v after expr-first is “definitely assigned after false expression”, and the state of v after expr-second is “definitely assigned after false expression”, then the state of v after expr is “definitely assigned after false expression”.

    o Otherwise, the state of v after expr is not definitely assigned.

    So this makes it clear that expr-first is always evaluated and if true then, and only then, expr-second is also evaluated.

    0 讨论(0)
  • 2020-12-08 20:16

    The && and || operators short-circuit. That is:

    1) If && evaluates its first operand as false, it does not evaluate its second operand.

    2) If || evaluates its first operand as true, it does not evaluate its second operand.

    This lets you do null check && do something with object, as if it is not null the second operand is not evaluated.

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