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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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}.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.