Search code examples
c#wpfoverridinggethashcode

What is wrong with my List<T>.Distinct()?


I have a class MyItems that implements IEqualityComparer and overrides the following methods:

public bool Equals(MyItems item1, MyItems item2)
{
    return (item1.ID == item2.ID && item1.itemName.Equals(item2));
}
public int GetHashCode(MyItems item)
{
    return item.ID.GetHashCode() ^ item.itemName.GetHashCode();
}

First, why is GetHashCode necessary? I understand overriding the Equals method, however, the GetHashCode necessity has eluded me.

Second, this doesn't appear to be working. Is there something I'm doing wrong here? Where I don't understand the GetHashCode, that maybe where I am tripping up.


Solution

  • To answer your first question, just look here for more information.

    To answer your second question: You forgot item2 should be item2.itemName

    return (item1.ID == item2.ID && item1.itemName.Equals(item2.itemName));