Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is order guaranteed in an or expression [duplicate]

I have an expression like this:

EqualByComparer comparer;
if (ListEqualByComparer.TryGetOrCreate(x, y, out comparer) ||
    EnumerableEqualByComparer.TryGetOrCreate(x, y, out comparer))
{
    return comparer.Equals(x, y, compareItem, settings, referencePairs);
}

Will ListEqualByComparer.TryGetOrCreate always be called before EnumerableEqualByComparer.TryGetOrCreate?

like image 975
Johan Larsson Avatar asked Apr 06 '16 10:04

Johan Larsson


4 Answers

Will ListEqualByComparer.TryGetOrCreate always be called before EnumerableEqualByComparer.TryGetOrCreate?

Yes, and as || is short-circuiting, the second call will only be made if the first call returns false.

From the C# 5 specification, section 7.12.1:

When the operands of && or || are of type bool, or when the operands are of types that do not define an applicable operator & or operator |, but do define implicit conversions to bool, the operation is processed as follows:

[...]

The operation x || y is evaluated as x ? true : y. In other words, x is first evaluated and converted to type bool. Then, if x is true, the result of the operation is true. Otherwise, y is evaluated and converted to type bool, and this becomes the result of the operation.

like image 168
Jon Skeet Avatar answered Oct 18 '22 21:10

Jon Skeet


Yes - details are in the documentation.

The second condition is only evaluated if the first is false

like image 21
Stuart Whitehouse Avatar answered Oct 18 '22 20:10

Stuart Whitehouse


From C# Reference (link):

The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.

like image 40
Nikola.Lukovic Avatar answered Oct 18 '22 19:10

Nikola.Lukovic


Yes, the order is guaranteed. MSDN states:

Logical operators also guarantee evaluation of their operands from left to right. However, they evaluate the smallest number of operands needed to determine the result of the expression. This is called "short-circuit" evaluation. Thus, some operands of the expression may not be evaluated.

like image 44
Bill Tür stands with Ukraine Avatar answered Oct 18 '22 20:10

Bill Tür stands with Ukraine