Why do I need to override the .Equals and GetHashCode in C#
c#
Solution
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.
Problem
I am using Entity Framework 5. In my C# code I want to compare if two objects are equal. If there are not then I want to issue an update. I have been told I need to override the .Equals method and then also the gethascode method. My classes look like this: ``` public class Students { public int PersonId { get; set; } public string Name { get; set; } public int Age {get; set;} } ``` Can some explain why I need to override .Equals and .GetHashCode. Also can someone give me an example. In particular I am not sure about the hashcode. Note that my PersonId is a unique number for this class.