3

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.

gdoron
  • 147,333
  • 58
  • 291
  • 367
B-Rad
  • 1,519
  • 5
  • 17
  • 32
  • 8
    return (item1.ID == item2.ID && item1.itemName.Equals(item2.**itemName**)); – I4V Jan 02 '13 at 22:52
  • 1
    If your `MyItems` class itself implements `IEqualityComparer` there's something wrong. **Either:** Override `Equals(object)` (one parameter) and override `GetHashCode()` (zero parameters). **Or:** Write _another_ class for comparing `MyItems`; the best way is to derive from the abstract [`EqualityComparer<>`](http://msdn.microsoft.com/en-us/library/ms132123.aspx) class. – Jeppe Stig Nielsen Jan 02 '13 at 23:20

3 Answers3

8

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));
Community
  • 1
  • 1
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
  • 1
    Thank you for this! Pretty embarrassing, although not uncommon for me, to miss something like this! – B-Rad Jan 03 '13 at 13:20
6

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.

gdoron
  • 147,333
  • 58
  • 291
  • 367
1

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

Alexandar
  • 916
  • 2
  • 9
  • 22