Search code examples
c#.netclassgethashcode

C# .NET GetHashCode function question


Hi I have a class with 6 string properties. A unique object will have different values for atleast one of these fields

To implement IEqualityComparer's GetHashCode function, I am concatenating all 6 properties and calling the GetHashCode on the resultant string.

I had the following doubts:

  1. Is it necessary to call the GetHashcode on a unique value?
  2. Will the concatenation operation on the six properties make the comparison slow?
  3. Should I use some other approach?

Solution

  • GetHashCode does not need to return unequal values for "unequal" objects. It only needs to return equal values for equal objects (it also must return the same value for the lifetime of the object).

    This means that:

    1. If two objects compare as equal with Equals, then their GetHashCode must return the same value.
    2. If some of the 6 string properties are not strictly read-only, they cannot take part in the GetHashCode implementation.

    If you cannot satisfy both points at the same time, you should re-evaluate your design because anything else will leave the door open for bugs.

    Finally, you could probably make GetHashCode faster by calling GetHashCode on each of the 6 strings and then integrating all 6 results in one value using some bitwise operations.