I have a simple, generic container class in C# that looks something like this -
public class Point<T>
{
public T Data { get; }
public string ID { get; }
public Point(T x, string id)
{
this.Data = x;
this.ID = id;
}
}
I would like all Point objects to be compared solely based on the ID property. My question is - how can I implement IEquatable<Point> such that any Point objects can be compared to each other? For example, Point<int> could be compared to Point<decimal>, and the objects would be considered equal if their ID properties were identical.
A simple way is to extract a non-generic interface. Though it is not required for
IEquatable, you can even include theDataproperty in this interface.Though a caveat is that other code now can provide their own implementation of
IPointand their own implementation ofIEquatable<IPoint>, that isn't consistent with yourPoint<T>. This could cause confusing behaviours such asimplA.Equals(implB)not agreeing withimplB.Equals(implA).