Search code examples
c#gethashcode

Unexpected GetHashCode behavior in Vector3D


I have found some weird behavior with the Vector3D class.

Given two Vector3Ds with rearranged X/Y/Z values (e.g. [0,0,1], [0,1,0] or [3,1,4],[1,3,4]), calling GetHashCode results in the same value. If you check to see if the vectors are equal via .Equals or ==, as expected you see that the two vectors are in fact not equal.

If they are not equal, why would they have the same hash code?

var a = new System.Windows.Media.Media3D.Vector3D(0, 0, 1);
var b = new System.Windows.Media.Media3D.Vector3D(0, 1, 0);

var equal  = a == b; // false
var equals = a.Equals(b); // false
var aHashCode = a.GetHashCode(); // 1072693248
var bHashCode = b.GetHashCode(); // 1072693248
var hashEqual = a.GetHashCode() == b.GetHashCode(); // true

PS: I have also observed this behavior in the Point3D class as well. Perhaps other classes in System.Windows.Media namespace are also affected.


Solution

  • Two different objects can have the same hash code. Two equal objects alwasy have the same hash code.

    As it is stated in MSDN

    Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value this method returns may differ between .NET Framework versions and platforms, such as 32-bit and 64-bit platforms. For these reasons, do not use the default implementation of this method as a unique object identifier for hashing purposes.