4

Duplicate: What is the best algorithm for an overridden System.Object.GetHashCode?


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?

Community
  • 1
  • 1
abelenky
  • 63,815
  • 23
  • 109
  • 159

1 Answers1

1

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
  • 105,752
  • 40
  • 168
  • 205
  • 4
    This approach has serious performance implications. Considering where GetHashCode is used, this seems effective, but unwise. – abelenky Jan 14 '09 at 01:54