All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1206.html Maven / Gradle / Ivy

There is a newer version: 9.32.0.97167
Show newest version

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy