Report MA0179 when the constant is on the left of the length comparison
What
UseAttributeIsDefinedAnalyzer (MA0179) only detected GetCustomAttributes().Length / .Count() existence checks when the length was the left operand. The reversed form was silently missed:
member.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0 // MA0179 reported
0 < member.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length // no diagnostic
Why
IsValidLengthComparisonPattern takes a lengthIsOnLeft flag and carefully implements both orientations. But both call sites hard-coded lengthIsOnLeft: true and only ever passed (operation.LeftOperand, operation.RightOperand) in that order, so the entire else block was unreachable dead code.
IsGetCustomAttributeComparison (the == null variant) already handles both orientations, which makes the asymmetry an oversight rather than a deliberate scope decision — so this fixes it rather than deleting the branch.
Changes
AnalyzeBinarynow tries both operand orders for theLengthandCount()comparisons, passing the orientation through toIsValidLengthComparisonPatterninstead of hard-codingtrue.- Renamed the
left/rightparameters of the two helpers tolengthOperand/countOperandandotherOperand, since they no longer correspond to syntactic sides. - Documented the reversed form in
docs/Rules/MA0179.md.
Note for reviewers
The code fixer needed no change. ShouldNegateLengthComparison already implemented both orientations and already searched both operands — it was dead in exactly the same way as the analyzer's else block, and simply becomes live now. That is why the diff touches only the analyzer.
Tests
15 new cases in UseAttributeIsDefinedAnalyzerTests, each asserting the diagnostic and the fixed code, so the negation direction is verified rather than just detection:
- 6 reversed
Lengthforms added to the existing theory:0 == len→!IsDefined,0 != len→IsDefined,0 < len→IsDefined,1 <= len→IsDefined,1 > len→!IsDefined,0 >= len→!IsDefined - 6 equivalent reversed
Count()forms - 3 negative cases confirming ambiguous reversed comparisons stay unreported (
0 > len,1 == len,2 <= len)
Verification
dotnet test --max-parallel-test-modules 2across all five Roslyn versions: 22751 passed, 0 failed.- Confirmed the new tests actually ran by checking the test names in the
.trxoutput rather than relying on the pass count. dotnet run --project src/DocumentationGeneratorexits 0 with no further markdown changes.