0

Is there a.NET utility class equivalent to java.util.Arrays.hashCode() for arrays of intrinsic types such as int[], short[], float[], etc.?

Obviously I could write my own utility class but was trying to find one already available in the .NET framework.

David G
  • 6,249
  • 4
  • 33
  • 31

3 Answers3

2

In .NET 4.0 arrays will support this via the IStructuralEquatable interface, but until that point you'll have to do it yourself I'm afraid.

Greg Beech
  • 133,383
  • 43
  • 204
  • 250
1

I'm pretty sure there's nothing in the framework itself that does this. There may well be some third-party implementations, but there's nothing built-in (and public).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

I'm not aware of such a thing being built-into .Net up to version 3.5, although .Net 4 is very likely to support it natively via the IStructuralEquatable interface which Array will implement (thanks to Greg Beech for pointing that out).

Here's a simple implementation using an extension method on IEnumerable.

int HashContents<T>(this IEnumerable<T> enumerable)
{
    int hash = 0x218A9B2C;
    foreach (var item in enumerable)
    {
        int thisHash = item.GetHashCode();
        //mix up the bits.
        hash = thisHash ^ ((hash << 5) + hash);
    }
    return hash;
}

This will give different hashcodes for {0,0} and {0,0,0}.

Matt Howells
  • 40,310
  • 20
  • 83
  • 102
  • Two quick questions: 1) Is it really faster to do the shift and add rather than just multiply? 2) As far as I can tell, if the value of thisHash is always zero, then the final hash will be zero, no matter how many items. This seems to contradict your last sentence. – Steven Sudit Jul 24 '09 at 15:22
  • 1) In Release mode, VS2008, my micro-benchmarks indicate the shift-and-add version peforms about 8% faster than the equivalent multiplication. 2) Thanks, code has been fixed. – Matt Howells Jul 27 '09 at 09:01