Saturday, November 12, 2011

Equality Operators of Complex POCOs

Usually I just hit "Alt+Insert" and ReSharper generates these methods correctly, but when your POCOs are composed of collections you will run into this little inconsistency. None of the .Net collections override the Equality operators, that means you will not be able to use your object as a Hash Key.

System.Linq.Enumerable comes to the rescue with SequenceEqual and Sum!

Use it in the Equals method like so:
bool equal = other._fields.SequenceEqual(_fields);

GetHashCode looks something like:
int hashCode = _fields.Sum(field => field.GetHashCode());

Have fun!

Update: Nov 21, 2011
Turns out using Sum is a mistake! There is a high probability that the sum of the hash codes in the collection will exceed int.MAX_VALUE, which will in turn raise an OverflowException! I quick search using my favorite engine lead me to this article where the author provides a few solutions to the problem. I favored using the XOR to compute the composite hash code. The new implementation uses the Aggregate function and looks something like:
int hashCode = _fields.Aggregate(0, (total, field) => total ^ field.GetHashCode());  

No comments: