S1206 — "Equals(Object)" and "GetHashCode()" should be overridden in pairs

Language
C#
Type
Bug
Severity
Minor
Tags
cwe

Why is this an issue?

Suppose you override Object.Equals in a type, you must also override Object.GetHashCode. If two objects are equal according to the Equals method, then calling GetHashCode on each of them must yield the same integer. If this is not the case, many collections, such as a Hashtable or a Dictionary won’t handle class instances correctly.

In order to not have unpredictable behavior, Equals and GetHashCode should be either both inherited, or both overridden.

How to fix it

When you override Equals then you have to also override GetHashCode. You have to override both of them, or simply inherit them.

Code examples

Noncompliant code example


class MyClass   // Noncompliant: should also override GetHashCode
{
    public override bool Equals(object obj)
    {
        // ...
    }
}

Compliant solution


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

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

Resources

Documentation

↑ Back to top