Wednesday, October 28, 2009

GetHashCode is useful, who knew?

If you’re like me, you’re inclined to lazily ignore warnings to override object.GetHashCode for your custom types if you’ve already overriden object.Equals.  If I’m using a Dictionary and using one of my objects as a key, then sure, I can see the point.  But if I’m just throwing it in a generic List, object.Equals is good enough, right?

Well, yes, but apparently this isn’t a safe assumption to make for any given collection type or operation.  I learned this the hard way with LINQ’s Enumerable.Intersect method (an extension method of IEnumerable<T>).

Without going into detail about set theory, the Enumerable.Intersect method will take two collections of objects, and return a collection of objects which both source sets contain.  So, for example, if I have two sets of ints:

A = { 1, 5, 7, 9 }
B = { 4, 5, 9, 13 }

The intersected set would contain only the values that both sets share:

{ 5, 9 }

Now, if the items in my sets are of my own custom type, I thought it would be sufficient to override object.Equals for this type.  But no, if I do this, Enumerable.Intersect will return an empty collection, indicating that none of the objects are equal, even if they areWhen I implemented object.GetHashCode as the compiler repeatedly pestered me to do, everything worked fine.

No comments: