When writing my own immutable ByteArray
class that uses an internal byte array, I implemented the IStructuralEquatable
interface. In my implementation, I delegated the task of computing hash codes for an internal array. During testing, to my great surprise, I found that my two different arrays had the same structural hash code, i.e. They returned the same value from GetHashCode
. Playback:
IStructuralEquatable array11 = new int[] { 1, 1 }; IStructuralEquatable array12 = new int[] { 1, 2 }; IStructuralEquatable array22 = new int[] { 2, 2 }; var comparer = EqualityComparer<int>.Default; Console.WriteLine(array11.GetHashCode(comparer));
IStructuralEquatable
is completely new and unknown, but I read somewhere that it can be used to compare the contents of collections and arrays. Am I mistaken, or is my .Net wrong?
Please note that I'm not talking about Object.GetHashCode
!
Edit: Thus, I am apparently mistaken, since unequal objects can have the same hash codes. But doesn't GetHashCode
mean returning some randomly distributed set of values? After some testing, I found that any two arrays with the same first element have the same hash. I still think this is strange behavior.
source share