Fix MA0141, MA0142, MA0148 and MA0149 false positives on dynamic operands

Merged
ME
2mo ago
+54-0

What

MA0141, MA0142, MA0148 and MA0149 reported comparisons with a dynamic operand:

dynamic d = 1L;
_ = d == 1;    // MA0148, fixed as 'd is 1'
_ = d == null; // MA0142, fixed as 'd is null'

Replacing them with a pattern changes the behavior:

  • d == 1 is bound at runtime with the runtime types of the operands (long == int, which is true), whereas d is 1 tests the runtime type of the value ((object)1L is 1 is false).
  • d == null is bound at runtime, and calls the user-defined == operator of the runtime type of d when there is one, whereas d is null is always a reference null check.

Expected: no diagnostic, actual: MA0148 / MA0149 / MA0142 / MA0141.

Fix

UsePatternMatchingForEqualityComparisonsAnalyzer skips the equality and inequality operations whose left or right operand is dynamic, for both the null checks and the constant comparisons. The documentation of the four rules mentions it.

Tests

Added DynamicOperand, covering == / != against a constant and null on both sides, and a comparison with a non-constant value. Ran UsePatternMatchingForEqualityComparisonsAnalyzer* tests (including the HasValue tests) on roslyn5.9 (55/55 passed) and roslyn4.8 (55/55 passed).