Enforces that base is object when using base.Equals

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

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