Just wondering if what I mentioned in the title is a good practice. It makes sense to me, we’re overriding GetHashCode to return a value based on two properties that if match, the two objects should be treated as equal. Logic seems fine and the code works, but I don’t know if it can cause other problems.
This is using GetHashCode:
public static bool operator ==(CartesianCoordinates a, CartesianCoordinates b)
{
return a.GetHashCode() == b.GetHashCode(); // Using GetHashCode here
}
public static bool operator !=(CartesianCoordinates a, CartesianCoordinates b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
return this == (CartesianCoordinates)obj; // This just uses the == override
}
public override int GetHashCode()
{
return (this.X + this.Y.ToLower()).GetHashCode(); // GetHashCode hashes the two properties we care about
}
And this is how I had it before:
public static bool operator ==(CartesianCoordinates a, CartesianCoordinates b)
{
return a.X == b.X && string.Equals(a.Y, b.Y, StringComparison.CurrentCultureIgnoreCase); // The difference is here
}
public static bool operator !=(CartesianCoordinates a, CartesianCoordinates b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
return this == (CartesianCoordinates)obj;
}
public override int GetHashCode()
{
return (this.X + this.Y.ToLower()).GetHashCode();
}
Important Note:
In the CartesianCoordinates object, X is an int and Y is a string:
public int X { get; set; }
public string Y { get; set; }
Lmk, thanks in advance!
Doing this is not only bad practice, it’s just wrong! Two objects that are equal must have the same hashcode, but the opposite is not true: two different objects can have the same hashcode (and often will). So if you use the hashcode to decide whether or not the objects are equal, in some case you will consider them equal when they’re actually different but just happen to have the same hashcode. A hashcode is not a unique identifier…
Based on your
GetHashCodeimplementation, objects with coordinates(x, y)and(y, x)will be considered equal (sincex + y == y + x)