What is the best algorithm for overriding GetHashCode?

 

The GetHashCode method is used to generate a hash code for an object in C#. A good GetHashCode implementation should produce hash codes that are as evenly distributed as possible to minimize collisions while remaining consistent with the object's state. Here's an example of a recommended approach to implementing GetHashCode.

csharp
public class Person { public string FirstName { get; } public string LastName { get; } public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public override int GetHashCode() { unchecked { int hash = 17; // Initialize with a prime number hash = hash * 23 + FirstName?.GetHashCode() ?? 0; // Include FirstName hash = hash * 23 + LastName?.GetHashCode() ?? 0; // Include LastName return hash; } } public override bool Equals(object obj) { if (obj is Person other) { return FirstName == other.FirstName && LastName == other.LastName; } return false; } }

In this example:

  1. We override the GetHashCode method.
  2. We use the unchecked block to avoid integer overflow exceptions.
  3. We initialize the hash variable with a prime number (17) to start the hash code generation.
  4. We multiply the hash by another prime number (23) and add the hash code of the FirstName property, and repeat the same for the LastName property.
  5. We include null checks (?? 0) for the properties to ensure that null values don't cause exceptions.

This approach ensures that the hash code depends on the object's state (in this case, the FirstName and LastName properties) and provides a relatively good distribution of hash codes, reducing the likelihood of collisions.

Keep in mind that while this is a recommended approach, the specific implementation may vary depending on the characteristics of your object's properties and your performance requirements. It's important to choose hash code components that are likely to vary for distinct objects and to use prime numbers to help achieve a good distribution of hash codes.

Comments