In .NET you need that Equals(object) and GetHashCode() are compatible. But sometimes you can't:
public class GreaterThan32Bits
{
public int X { get; set; }
public int Y { get; set; }
}
Because the data density is greater than 32 bits, and GetHashCode returns an Int32, you will have 3 solutions (assuming a correctly implemented GetHashCode):
Avoid code duplicationdiscarded as incorrectpublic override bool Equals(object other) { if(ReferenceEquals(null, other)) return false; if(ReferenceEquals(this, other)) return true; return this.GetHashCode() == other.GetHashCode(); }
Implement Equals separately from GetHashCode()
public override bool Equals(object obj) { if(ReferenceEquals(null, other)) return false; if(ReferenceEquals(this, other)) return true; var other = obj as GreaterThan32Bits; if(this.X == other.X) return this.Y == other.Y; return false; }
Implement a greater precision GetHashCode64, the overrided GetHashCode (32 bits) will return (int)GetHashCode64(), and Equals will return this.GetHashCode64() == other.GetHashCode64()
Which one would you implement?
The first solution is imprecise incorrect, but cleaner. The second option seems clean, but gets very complex when the class has more properties. The third option is a compromise.