I have an abstract base class Shape with three derived classes: Arc
, Circle
, and Rectangle
. I have implemented an equality check in these classes, and I want to consider Arcs
equal to Circles
if they have the same shape. To do this, I check the type of the Shape
, downcast it, and then perform additional checks to determine if the two Shapes
represent the same geometry. However, I am concerned that this approach may be a code smell and may not be the correct way to handle this situation. For example, if someone were to inherit from Shape
in the future and create a class that can have a similar shape to an Arc
, my current approach would not work. Is there a better way to handle this situation? My current code looks like this:
public abstract class Shape : IEquatable<Shape>
{
public abstract bool Equals(Shape other);
}
public class Arc : Shape
{
public override bool Equals(Shape other)
{
if (other is Arc || other is Circle)
{
// Downcast and check for equality criteria!!
}
else
{
return false;
}
}
}
public class Circle : Shape
{
public override bool Equals(Shape other)
{
if (other is Arc || other is Circle)
{
// Downcast and check for equality criteria!!
}
else
{
return false;
}
}
}
public class Rectangle : Shape
{
public override bool Equals(Shape other)
{
if (other is Rectangle)
{
// Downcast and check for equality criteria!!
}
else
{
return false;
}
}
}
UPDATE:
After considering the answers and thinking further, I believe I need to change my design as follows: the Shape
class should have methods like IsEqualToCircle(Circle circle)
and IsEqualToArc(Arc arc)
. Then, in the equality check for the Arc
class, I can write if (shape.IsEqualToArc(this)) return true;
and so on. The example shown here is just a simplification to illustrate a problem I have encountered in many situations. Of course, this is not real code