If an interface inherits IEquatable the implementing class can define the behavior of the Equals method. Is it possible to define the behavior of == operations?
public interface IFoo : IEquatable {} public class Foo : IFoo { // IEquatable.Equals public bool Equals(IFoo other) { // Compare by value here... } }
To check that two IFoo references are equal by comparing their values:
IFoo X = new Foo(); IFoo Y = new Foo(); if (X.Equals(Y)) { // Do something }
Is it possible to make if (X == Y) use the Equals method on Foo?
No – you can’t specify operators in interfaces (mostly because operators are static). The compiler determines which overload of == to call based purely on their static type (i.e. polymorphism isn’t involved) and interfaces can’t specify the code to say ‘return the result of calling X.Equals(Y)’.