roslynator icon indicating copy to clipboard operation
roslynator copied to clipboard

RCS1132 false positive (and conflict with CS8851)

Open eduherminio opened this issue 4 years ago • 3 comments

Product and Version Used:

  • Roslynator 2019 3.0.1 (VS 2019 extension)
  • .NET 5.0

Steps to Reproduce:

public record Foo(int A)
{
    public virtual bool Equals(Foo? other)
    {
        if (other is null)
        {
            return false;
        }

        return A.Equals(other.A);
    }

    public override int GetHashCode() => A.GetHashCode();
}

public record Bar(int A, int B) : Foo(A)
{
    public virtual bool Equals(Bar? other) => base.Equals(other); // CS8851 if you don't add the next line

    public override int GetHashCode() => base.GetHashCode(); // RCS1132, but removing the method implies a behavior change
}

Actual Behavior: RCS1132

Expected Behavior: No action triggered.

eduherminio avatar Nov 11 '20 01:11 eduherminio

But why would you (in a real world) intentionally call GetHashCode from a base class?

josefpihrt avatar Nov 15 '20 22:11 josefpihrt

I don't know how much sense does it make, but I'm playing with these kind of records (see https://github.com/dotnet/csharplang/discussions/4122#discussioncomment-126027 for more details):

public record Node(string Id)
{
    public virtual bool Equals(Node? other)
    {
        if (other is null)
        {
            return false;
        }

        return Id.Equals(other.Id);
    }

    public override int GetHashCode() => Id.GetHashCode();
}

public record TreeNode(string Id, ICollection<TreeNode> Children) : Node(Id)
{
    public override bool Equals(TreeNode? other) => base.Equals(other);

    public override int GetHashCode() => base.GetHashCode();
}

eduherminio avatar Nov 15 '20 23:11 eduherminio

If calling a custom implemented GetHashCode as in this example, it does not make sense but if we are calling the compiler generated GetHashCode it is ok to use it because hash code of EqualityContract property is also combined.

nvmkpk avatar Mar 30 '21 18:03 nvmkpk