Possible Duplicate:
Can I overload an == operator on an Interface?
I do understand how to overload operator== for a single class. I even made it work with inheritance. But I don’t seem to be able to implement it for an interface. Imagine the following:
IFoo foo1 = new Foo(42);
IFoo foo2 = new Foo(42);
Assert.IsTrue( foo1 == foo2 ); // fails
As you might have guessed I want classes implementing IFoo behave like a value type (at least when comparing for equality). As you can see the concrete type Foo of foo1 and foo2 is no longer “known” when the Assert happens. All that is known is their interface IFoo.
Of course I could use IEquatable<IFoo> and write foo1.Equals(foo2) instead, but that is not the point here. And if IFoo were an abstract base class instead of an interface I could overload operator== no problem. So how do I do the same for an interface?
The problem basically boils down to being unable to write the following, because at least one of left and right must be Foo:
public interface IFoo : IEquatable<IFoo>
{
int Id { get; }
}
public class Foo : IFoo
{
public int Id { get; private set; }
... // some implementation here
public static bool operator== ( IFoo left, IFoo right ) // impossible
{
... // some null checks here
return left.Id == right.Id;
}
}
Is overloading operator== for an interface impossible or is there a trick I missed?
It isn’t possible to overload an operator on an interface. At their core overloaded operators are basically static methods which the compiler maps operators to. This means overloaded operators have all of the same issues that static methods in an interface do and hence are disallowed.
The best way to specify that an interface has non-reference equality semantics is to have it derive from
IEquatable<T>. This is by no means a binding commitment for the caller or implementer but it’s a hint to both.