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?