Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/Rules/MA0073.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ if (!value)
{
}
```

The rule only reports the built-in `bool` equality operators. It does not report the comparisons that use a user-defined operator, such as `operator ==(MyType, bool)`, as removing the constant would change the meaning of the code.
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ private static void AnalyzeBinaryOperation(OperationAnalysisContext context)
return;
}

// Only the built-in bool operators can be replaced by the operand
if (binaryOperation.OperatorMethod is not null)
return;

// There must be 2 valid operands
if (binaryOperation.LeftOperand?.Type is null || binaryOperation.RightOperand?.Type is null)
return;
Expand Down Expand Up @@ -63,6 +67,9 @@ private static void AnalyzeBinaryOperation(OperationAnalysisContext context)
return;
}

if (!nodeToKeep.Type.IsBoolean())
return;

// The fixer will need to prefix the remaining operand with '!' if the original comparison is "!= true" or "== false"
var logicalNotOperatorNeeded = (bool)nodeToRemove.ConstantValue.Value! ?
binaryOperation.OperatorKind == BinaryOperatorKind.NotEquals :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,4 +390,23 @@ void Test(long? number)

return test.RunAsync();
}

[Fact]
public Task ComparingWithUserDefinedOperator_NoDiagnosticReported()
{
var test = CreateTest();
test.TestCode = """
class C
{
public static bool operator ==(C a, bool b) => true;
public static bool operator !=(C a, bool b) => false;
public override bool Equals(object o) => true;
public override int GetHashCode() => 0;

bool M(C c) => c == true;
}
""";

return test.RunAsync();
}
}
Loading