What are the rules I should follow to ensure GetHashCode() method returns unique value for an object?
For example:
- Should I include some prive members for the calculation?
- Should I multiply instead of sum?
- Can I be sure that I am generating a uniqe hash code for a particular object graph? etc.
You shouldn’t even aim for
GetHashCode()returning a unique value for each object. That’s not the point ofGetHashCode().Eric Lippert has a great post about hash codes which you should read thoroughly. Basically you want to end up with something which will always return the same value for two equal objects (and you need to work out what you mean by equal) and is likely to return different values for two non-equal objects.
Personally I tend to use an implementation like this:
Things to watch out for:
If your fields can be null, you need to check for that while calculating your hash. For example: