Why do I need to override the .Equals and GetHashCode in C#

You need to override the two methods for any number of reasons. The GetHashCode is used for insertion and lookup in Dictionary and HashTable, for example. The Equals method is used for any equality tests on the objects. For example:

public partial class myClass
{
  public override bool Equals(object obj)
  {
     return base.Equals(obj);
  }

  public override int GetHashCode()
  {
     return base.GetHashCode();
  }
}

For GetHashCode, I would have done:

  public int GetHashCode()
  {
     return PersonId.GetHashCode() ^ 
            Name.GetHashCode() ^ 
            Age.GetHashCode();
  }

If you override the GetHashCode method, you should also override Equals, and vice versa. If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

Tags:

C#