I have read that when you override Equals on an class/object you need to override GetHashCode.
public class Person : IEquatable
{
You should always override GetHashCode
.
A Dictionary
will function without GetHashCode
, but as soon as you call LINQ methods like Distinct
or GroupBy
, it will stop working.
Note, by the way, that you haven't actually overridden Equals
either.
The IEquatable.Equals
method is not the same as the virtual bool Equals(object obj)
inherited from Object
. Although the default IEqualityComparer
will use the IEquatable
interface if the class implements it, you should still override Equals
, because other code might not.
In your case, you should override Equals
and GetHashCode
like this:
public override bool Equals(object obj) { return Equals(obj as Person); }
public override int GetHashCode() {
return FirstName.GetHashCode() ^ LastName.GetHashCode();
}