Sobes.tech
Junior — Middle

Perché è importante sovrascrivere il metodo GetHashCode nelle classi?

sobes.tech AI

Risposta dell'AI

La sovrascrittura del metodo GetHashCode è importante per il corretto funzionamento degli oggetti nelle collezioni basate su hash, come Dictionary, HashSet e altre.

Motivi:

  • GetHashCode restituisce un valore numerico utilizzato per trovare rapidamente un oggetto nelle tabelle hash.
  • Se due oggetti sono considerati uguali (secondo il metodo Equals), devono restituire lo stesso hash code affinché le collezioni li gestiscano correttamente.
  • Se GetHashCode non viene sovrascritto insieme a Equals, gli oggetti potrebbero essere confrontati in modo errato o duplicati nelle collezioni.

Esempio:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Person other)
            return Name == other.Name && Age == other.Age;
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
}

In questo modo, la sovrascrittura di GetHashCode garantisce la coerenza con Equals e il corretto funzionamento degli oggetti nelle strutture hash.