Skip to content

[C#] False positive in cs/simplifiable-boolean-expression for operator != implementation #22190

Description

@christiannagel

Description of the false positive

The C# query cs/simplifiable-boolean-expression suggests rewriting !(A == B) to A != B. This is generally correct, but it is unsafe inside an operator != implementation when operator != is defined in terms of operator ==.

In that context, applying the suggestion creates self-recursion:

  • Original (correct): operator != delegates to !(left == right)
  • Suggested rewrite: left != right
  • Result: operator != calls itself recursively (infinite recursion / stack overflow)

So this is a false positive for this specific pattern.

Code samples or links to source code

Repository:
https://github.com/CNinnovation/dotnet-templates

Code sample:

public static bool operator ==(MarkedClassInfo? left, MarkedClassInfo? right) =>
    left is null ? right is null : left.Equals(right);

public static bool operator !=(MarkedClassInfo? left, MarkedClassInfo? right) => !(left == right);

File:
https://github.com/CNinnovation/dotnet-templates/blob/main/templates/SourceGeneratorTemplate/content/MyGenerator/MyGeneratorImpl.cs

URL to the alert on GitHub code scanning (optional)

https://github.com/CNinnovation/dotnet-templates/security/quality/rules/cs%2Fsimplifiable-boolean-expression

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions