Enforces that base is object when using base.Equals

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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

PREVIEWING: rtrieu/product-analytics-ui-changes