I have read that when you override Equals on an class/object you need to override GetHashCode.
public class Person : IEquatable<Person>
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(int personId, string firstName, string lastName)
{
PersonId = personId;
FirstName = firstName;
LastName = lastName;
}
public bool Equals(Person obj)
{
Person p = obj as Person;
if (ReferenceEquals(null, p))
return false;
if (ReferenceEquals(this, p))
return true;
return Equals(p.FirstName, FirstName) &&
Equals(p.LastName, LastName);
}
}
Now given the following:
public static Dictionary<Person, Person> ObjDic= new Dictionary<Person, Person>();
public static Dictionary<int, Person> PKDic = new Dictionary<int, Person>();
Will not overridding the GetHashCode affect both of the Dictionary’s above? What I am basically asking is how is GetHashCode generated? IF I still look for an object in PKDic will I be able to find it just based of the PK. If I wanted to override the GetHashCode how would one go about doing that?
You should always override
GetHashCode.A
Dictionary<int, Person>will function withoutGetHashCode, but as soon as you call LINQ methods likeDistinctorGroupBy, it will stop working.Note, by the way, that you haven’t actually overridden
Equalseither.The
IEquatable.Equalsmethod is not the same as thevirtual bool Equals(object obj)inherited fromObject. Although the defaultIEqualityComparer<T>will use theIEquatable<T>interface if the class implements it, you should still overrideEquals, because other code might not.In your case, you should override
EqualsandGetHashCodelike this: