Reputation: 1557
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.
Upvotes: 3
Views: 172
Reputation: 150263
The Distinct
method works as follows:
GetHashCode
.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.
Upvotes: 6
Reputation: 936
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
Upvotes: 1
Reputation: 16137
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));
Upvotes: 8