Search code examples
hashcodegethashcode

is this GetHashCode good enough?


I have this class:

public class RelationInfo
{
    public FieldInfo Field;
    public int Index;
    public override int GetHashCode()
    { return Field.GetHashCode() ^ int.GetHashCode(); }
    public override bool Equals(object obj)
    { return Field == ((RelationInfo)obj).Field && Index == ((RelationInfo)obj).Index; }
}

Is the GetHashCode in it well defined? I've read about FNV-like algorithms, but finally I come to the simple XOR. The reason is that the 2 fields are already well hashed respectively, and since the 2 fields are of different types, there's no need to worry about symmetric pair collision (like XORing x and y of a 2D point), so the only collision situation is that the 2 fields are both different but happen to get the same code after XORing, which is rare and acceptable.


Solution

  • Yes, that GetHashCode is fine. If you want to avoid the symmetry, apply some simple arithmetic one of the values, such as negating it. But every user of GetHashCode must handle collisions anyhow, so it's probably not needed.