== Why is this an issue?

Suppose you override https://learn.microsoft.com/en-us/dotnet/api/system.object.equals[Object.Equals] in a type, you must also override https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode[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 https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable[Hashtable] or a https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2[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

[source,csharp,diff-id=1,diff-type=noncompliant]
----
class MyClass   // Noncompliant: should also override GetHashCode
{
    public override bool Equals(object obj)
    {
        // ...
    }
}
----

==== Compliant solution

[source,csharp,diff-id=1,diff-type=compliant]
----
class MyClass
{
    public override bool Equals(object obj)
    {
        // ...
    }

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

== Resources

=== Documentation

* CWE - https://cwe.mitre.org/data/definitions/581[CWE-581 - Object Model Violation: Just One of Equals and Hashcode Defined]
* https://learn.microsoft.com/en-us/dotnet/api/system.object.equals[Object.Equals Method] 
* https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode[Object.GetHashCode Method]
* https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable[Hashtable class]  
* https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2[Dictionary<TKey,TValue> Class] 


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

This [class|struct] overrides "GetHashCode()|Equals()" and should therefore also override "GetHashCode()|Equals()".


=== Highlighting

The [class|struct] name.


'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
