I'm overwriting the GetHashCode()
Function for my Vector class. Its just contaning 3 floats X
, Y
, Z
. I'm wondering whats the best way to do so.
public override int GetHashCode()
{
var sum = X + 3 * Y + 5 * Z;
return sum.GetHashCode();
}
I need this to quickly find a Vector in a big-Collection.
I don't want to just return X.GetHashCode()
or so, because this would lead to too many equals checks for straight lines.
The problem with my current implementation is that, if the floats are really big I might get an integer overflow.
Is there a way to tell my compiler to just cut out any overflow?
Is there a better Solution?
Thanks in advance.
Often, when we combine hash codes manually, we do it with xor:
public override int GetHashCode() =>
X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
See Why is XOR the default way to combine hashes? for details
xor never throws any exception. You can let .Net to combine for you:
public override int GetHashCode() => HashCode.Combine(X, Y, Z);