Tuesday, July 30, 2013

Creating Hash Codes

Sometimes you need to override the Equals method and Microsoft suggests you should override also the GetHashCode method for better performance of hashing collections.
Here is a simple implementation of a HashCodeCalculator:
namespace Util
{
  // PRIMARY numbers
  private static int Base = 443;
  private static int Factor = 449;

  public static int Create(params object[] fields)
  {
    unchecked // Wrap on overflow 
    {
      int value = Base;

      foreach (var f in fields)
      {
        if (f != null)
          value = value * Factor + f.GetHashCode();
      }
      return value;
    }
  }
}

No comments:

Post a Comment