Consider, as an example, the following minimalistic Point class, which works with doubles:
public class Point
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public static Point operator +(Point left, Point right)
{
return new Point(left.X + right.X, left.Y + right.Y);
}
public static Point operator -(Point left, Point right)
{
return new Point(left.X - right.X, left.Y - right.Y);
}
}
The plus and minus operators make perfect sense to me. Running the Visual Studio 2013 Code Analysis, I get the warning CA1013: Overload operator equals on overloading add and subtract. I would implement this whole equality-thing as follows:
public static bool operator ==(Point point1, Point point2)
{
if (object.ReferenceEquals(point1, point2))
return true;
if (object.ReferenceEquals(null, point1))
return false;
return point1.Equals(point2);
}
public static bool operator !=(Point point1, Point point2)
{
return !(point1 == point2);
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(null, obj))
return false;
if (object.ReferenceEquals(this, obj))
return true;
if (obj.GetType() != this.GetType())
return false;
return this.IsEqual((Point)obj);
}
public bool Equals(Point point)
{
if (object.ReferenceEquals(null, point))
return false;
if (object.ReferenceEquals(this, point))
return true;
return this.IsEqual(point);
}
private bool IsEqual(Point point)
{
return this.X == point.X && this.Y == point.Y;
}
public override int GetHashCode()
{
return 571 + 821 * this.X.GetHashCode() + 307 * this.Y.GetHashCode();
}
However, when comparing two points, I would not use that kind of comparison, but rather compare the Points within a tolerance, since I am working with doubles. For this, I could use a 'NearlyEqual'-Method or something like that, but not '==' or 'Equals', since those methods have to be transitive.
Should I suppress the warning in a case like this, or are there any reasons why it could still make sense to implement 'Equals'?