Fix MA0141, MA0142, MA0148 and MA0149 false positives on dynamic operands
Merged
ME
2mo ago+54+54+01234567890123456789-0-0-0123456789
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 == 1is bound at runtime with the runtime types of the operands (long == int, which istrue), whereasd is 1tests the runtime type of the value ((object)1L is 1isfalse).d == nullis bound at runtime, and calls the user-defined==operator of the runtime type ofdwhen there is one, whereasd is nullis 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).