According to MSDN GetHashCode Method:
public struct Point
{
private int x;
private int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override bool Equals(Object obj)
{
if (!(obj is Point)) return false;
Point p = (Point) obj;
return x == p.x & y == p.y;
}
public override int GetHashCode()
{
return ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode();
}
private int ShiftAndWrap(int value, int positions)
{
positions = positions & 0x1F;
// Save the existing bit pattern, but interpret it as an unsigned integer.
uint number = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0);
// Preserve the bits to be discarded.
uint wrapped = number >> (32 - positions);
// Shift and wrap the discarded bits.
return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0);
}
}
I'm confused about the ShiftAndWrap Method, I know that is used to avoid generating collision hashcode. But I have questions as follows:
Why the parameter positions is set as 2?
Why the method do right-shift (32-positions) first then do left-shift positons, Does it have specific meaning?
As mentioned above, this method is used to reduce the situation of having collision, e.g. new Point(5,8) vs new Point(8,5), but if I create an object like new Point(3,16), it will get the same hashcode as new Point(5,8) did, so... what's the real effect of this method?