Enforces that base is object when using base.Equals

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Metadata

ID: csharp-best-practices/base-equals

Language: C#

Severity: Error

Category: Best Practices

Description

Using base.Equals can be dangerous when the base is not an object because the new base class can override Equals, leading to unexpected behavior. This rule prevents the use of base.Equals in a class where the base is not an object.

Non-Compliant Code Examples

class NonCompliant : Compliant
{
    private int bar;

    public override bool Equals(object other)
    {
        bool eq1;
        eq1 = base.Equals(other);
        var eq2 = base.Equals(other);
        if (base.Equals(other))
		{
            return true;
        }
        return this.bar == ((NonCompliant)other).bar;
    }
}

class Compliant
{
    private int foo;

    public override bool Equals(object other)
    {
        if (base.Equals(other))
		{
            return true;
        }
        return this.foo == ((Compliant)other).foo;
    }
}

Compliant Code Examples

class Compliant
{
    private int foo;

    public override bool Equals(object other)
    {
        if (base.Equals(other))
		{
            return true;
        }
        return this.foo == ((Compliant)other).foo;
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis