I have a wrapper class that will only have a single field and I want to override the GetHashCode method for the wrapper class.
I have written Hash Code algorithms in situations where there are multiple fields (i.e. using xor, shift-and-wrap, etc.) but this is the first time I've ever only had a single field to work with.
1) Should a wrapper and its field return the same hash code? My initial thought is no, it just doesn't feel right that we would knowingly design a class that generates the same hash as another class.
2) If not, would taking the field's hashcode and adding 1 to it suffice or is there a better way to calculate the new hashcode? The field class itself has a good algorithm for generating its hash codes.
Best How To :
As you're likely aware, you should override
Equals() when you want to customize the default equality behavior for the type, as used in various contexts but including hash-table based data structures like
There are some general rules to follow when doing this (most important being that if two instances your type are equal, they must have the same hash code value), but none of those rules involve worrying about whether a hash value may coincide with the value of an instance of some other type. Indeed, it's not even necessarily a problem if a hash value coincides with the value of an instance of the same type. Since
GetHashCode() returns a 32-bit integer, only types that have no more than than 2^32 possible values could even guarantee unique hash values for instances of the same type (e.g.
For example, for any given
long value (64-bit integer), there are 2^32-1 other
long values with the same hash code.
Which is a long way of saying…the simple implementation of just returning as your own type's value for its
GetHashCode() method, the value that your single field's
GetHashCode() method returns, is a perfectly acceptable and useful way to implement your
It's true that if for some reason you had an instance of the contained object's type and an instance of your own object's type in the same data structure, that there would be a collision (i.e. the two different instances having the same hash code value). But since collisions happen anyway when dealing with hash codes, that's not a problem.