tags:

views:

550

answers:

1

Duplicate: http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-systemobjectgethashcode


If you've written an object with a variety of data-members, how do you intelligently implement GetHashCode()?

One developer told me he just XORs (^ operator) the Hash of relevant data-fields, but I am unconvinced this is a "best-practices" implementation.

If I had my way, there would be functions Object.CombineHashes(Object[]), and/or Object.CombineHashes(int[]) to help intelligently build hashes of complex objects.

How would you write these functions?

A: 

I did a quick and dirty implementation of a bunch of members by concatenating them with pipes and then getting the hascode of that:

(Member1.ToString() + "|" + Member2.ToString()).GetHasCode();

In my case, I know that I won't ever have pipes in the members so I knew the results would be pretty good.

Actually, in my case I implemented ToString for debugging purposes so I just used that:

this.ToString().GetHashCode();

Xors is another approach I've often seen.

Michael Haren
This approach has serious performance implications. Considering where GetHashCode is used, this seems effective, but unwise.
abelenky