For a simple example, assume you have two classes that are different in many ways, but can still be considered "equateable":
class WholeNumber: IEquatable<WholeNumber> {
int value;
public override bool Equals(object obj) {
if (obj is IEquatable<WholeNumber>) {
IEquatable<WholeNumber> other = (IEquatable<WholeNumber>) obj;
return other.Equals(this);
} else {
return false;
}
}
public bool Equals(WholeNumber other) {
return this.value == other.value;
}
}
class Fraction : IEquatable<WholeNumber> {
WholeNumber numerator;
WholeNumber denominator;
public bool Equals(WholeNumber other) {
if (denominator != 1) {
// Assume fraction is already reduced
return false;
} else {
return this.numerator.Equals(other);
}
}
}
This will allow any object that claims to be equateable to WholeNumber to be passed into the WholeNumber's Equals(object) function and get the desired result without WholeNumber needed to know about any other class.
Is this pattern a good idea? Is using IEquatable with other classes a common (where it makes sence) thing to do?