views:

140

answers:

3

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.

+1  A: 

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
A: 

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
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
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
+2  A: 

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