Search code examples
c#algorithmarrayshashcode

C# hashcode for array of ints


I have a class that internally is just an array of integers. Once constructed the array never changes. I'd like to pre-compute a good hashcode so that this class can be very efficiently used as a key in a Dictionary. The length of the array is less than about 30 items, and the integers are between -1000 and 1000 in general.


Solution

  • Not very clever, but sufficient for most practical purposes:

    EDIT: changed due to comment of Henk Holterman, thanks for that.

      int hc = array.Length;
      foreach (int val in array)
      {
          hc = unchecked(hc * 314159 + val);
      }
    

    If you need something more sophisticated, look here.