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?

1
  • Nice find, @Gortok. I voted to close. Commented Jan 14, 2009 at 1:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.