What would be the best way to override the GetHashCode function for the case, when
my objects are considered equal if there is at least ONE field match in them.
In the case of generic Equals method the example might look like this:
public bool Equals(Whatever other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
// Considering that the values can't be 'null' here.
return other.Id.Equals(Id) || Equals(other.Money, Money) ||
Equals(other.Code, Code);
}
Still, I’m confused about making a good GetHashCode implementation for this case.
How should this be done?
Thank you.
This is a terrible definition of
Equalsbecause it is not transitive.Consider
Then
x == yandy == zbutx != z.Additionally, we can establish that the only reasonable implementation of
GetHashCodeis a constant map.Suppose that
xandyare distinct objects. Letzbe the objectThen
x == zandy == zso thatx.GetHashCode() == z.GetHashCode()andy.GetHashCode() == z.GetHashCode()establishing thatx.GetHashCode() == y.GetHashCode(). Sincexandywere arbitrary we have established thatGetHashCodeis constant.Thus, we have shown that the only possible implementation of
GetHashCodeisAll of this put together makes it clear that you need to rethink the concept you are trying model, and come up with a different definition of
Equals.