Question

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.

Was it helpful?

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));

OTHER TIPS

The Distinct method works as follows:

  1. Check if the two objects has the same hash code using GetHashCode.
  2. If they do, now make sure they absolutely equals with Equals.

The GetHashCode is a first check for the more expensive check: Equals

Your Equals method has an error:

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

Should be:

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

Also, if the List or the array type you're using isn't of <MyItems> type you also need to override the Equals method.

If you want to compare objects you should override Equals(object obj) in their class.

Also, whenever you override Equals(object obj) it is good practice to override GetHashCode

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top