4

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?

Community
  • 1
  • 1
Jonas Bötel
  • 4,452
  • 1
  • 19
  • 28

2 Answers2

4

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.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • It's a pity this is not supported and using a base class instead is not an option. At least there is a tiny bit of [tool support](http://stackoverflow.com/a/8536419/642532) to find usages of `operator==` instead of `.Equals`. – Jonas Bötel Mar 25 '12 at 15:56
1

You could define bool Equals(Object) in your interface instead of the operator and use Object.Equals(Object, Object) for the comparison.

This comparison is on class level then, not on interface level and could also involve other properties of the class in the comparison. If you wish to have a pure comparison of two interfaces ( compare the properties ), then you have to define your own static method which does this.

Felix K.
  • 6,201
  • 2
  • 38
  • 71