Overload operator == for an interface

Possible duplicate:
Can I overload the == operator on an interface?

I understand how to overload operator== for one class. I even did work with inheritance. But I can't seem 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 that implement IFoo to behave like a value type (at least when comparing for equality). As you can see, the specific type Foo foo1 and foo2 no longer “known” when Assert occurs. All that is known is their IFoo interface.

Of course, I could use IEquatable<IFoo> and write foo1.Equals(foo2) instead, but that is not the point here. And if IFoo was an abstract base class instead of an interface, I could overload operator== without any problems. So how do I do the same for the interface?

The problem basically boils down to the inability 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; } } 

Overloading operator== for an interface is not possible or is there a trick I missed?

+4
source share
2 answers

Unable to overload operator on interface. In their kernels, overloaded operators are mostly static methods to which the compiler maps operators. This means that overloaded operators have the same problems as static methods in the interface, and therefore are prohibited.

The best way to indicate that an interface has inappropriate equality semantics is to get it from IEquatable<T> . This is by no means an obligatory obligation for the caller or performer, but it is an allusion to both.

+4
source

You can define bool Equals(Object) in your interface instead of a statement and use Object.Equals(Object, Object) for comparison.

This comparison is performed at the class level, not at the interface level, and may also include other class properties when comparing. If you want to have a clean comparison of two interfaces (compare properties), then you must define your own static method that does this.

+1
source

Source: https://habr.com/ru/post/1403324/


All Articles