C#

C#

Made by DeepSource

Override GetHashCode and Equals if operators == and != are overloaded CS-W1031

Bug risk
Major

Equality operators are syntactically meant to mimic the Equals method which must always be overridden along with GetHashCode. Not doing so may produce inconsistent behavior when evaluating equalness and produces compiler warning CS0660. It is therefore recommended that you override both the GetHashCode and Equals methods in this case.

Bad Practice

class Foo
{
    public static bool operator ==(Foo f1, Foo f2)
    {
        // ...
    }

    public static bool operator !=(Foo f1, Foo f2)
    {
        // ...
    }
}

Recommended

class Foo
{
    public static bool operator ==(Foo f1, Foo f2)
    {
        // ...
    }

    public static bool operator !=(Foo f1, Foo f2)
    {
        // ...
    }

    public override int GetHashCode()
    {
        // ...
    }

    public override bool Equals(object? obj)
    {
        // ...
    }
}

Reference