Short circuiting statement evaluation — is this guaranteed? [C#]

后端 未结 6 2269
不思量自难忘°
不思量自难忘° 2020-12-10 11:53

Quick question here about short-circuiting statements in C#. With an if statement like this:

if (MyObject.MyArray.Count == 0 || MyObject.MyArray[0].SomeValu         


        
6条回答
  •  隐瞒了意图╮
    2020-12-10 12:42

    Yes, this is guaranteed.

    C# Language Specification - 7.11 Conditional logical operators:

    The && and || operators are called the conditional logical operators. They are also called the "short-circuiting" logical operators.

    Therefore they will support logical short-circuiting by definition - you can rely on this behavior.

    Now it is important to make a distinction between a conditional operator and a logical operator:

    • Only conditional operators support short-circuiting, logical operators do not.
    • C#'s logical operators look just like their conditional counterparts but with one less character so a logical OR is | and a logical AND is &.
    • Logical operators can be overloaded but conditional operators cannot (this is a bit of an technicality as conditional operator evaluation does involve overload resolution and this overload resolution can resolve to a custom overload of the type's logical operator, so you can work around this limitation to a certain extent).

提交回复
热议问题