Fix MA0172 false positive on operands with side effects
What
MA0172 compared the two operands by their syntax only. It reported operands that have the same text but can produce different values when evaluated twice:
_ = e.MoveNext() && e.MoveNext(); // advances the enumerator twice
_ = c++ == c++;
_ = (c = 1) == (c = 1);
_ = new object() == new object(); // always false
_ = await t && await t;
Expected: no diagnostic. Actual: MA0172.
Fix
The binary operation is no longer reported when the operands contain an operation that can produce a different value on each evaluation:
- an invocation (including dynamic invocations)
- an increment or decrement
- an assignment (including event assignments)
- an object creation (regular, dynamic, type parameter or anonymous)
- an
await
Behavior change: a call to the same method on both sides, such as a.Foo() == a.Foo() or string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s), is no longer reported. No existing test or documentation covered method calls. The analyzer cannot know whether a method is pure, so the rule now skips these operands rather than risk a false positive. Property accesses are still reported, as are pattern combinators (is true or true) and the d != d case.
The rule documentation describes the exception.
Tests
Added the SameCodeWithSideEffects theory (6 cases) to BothSideOfTheConditionAreIdenticalAnalyzerTests. All 6 cases failed before the fix. The class passes on roslyn5.9 and roslyn4.8 (24 tests each).