Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overload an == operator on an Interface?

I have an interface like this:

public interface IFoo
{
  int A {get;}
  int B {get;}
}

and I have multiple classes implementing IFoo.
I want to check equality, not based on ReferenceEquality, but two IFoos should be considered equal, if both A and B is the same (in reality I'm checking a collection of Key-Value pairs sent through WCF, that is why I can't have ReferenceEquality).
Now if I have:

IFoo first = new FooBar1() { A = 1, B = 1};
IFoo second = new FooBar2() { A = 1, B = 1};
if (first == second) {
 //this should return true
}

Currently IFoo is IEquatable<IFoo>, so FooBar1 and FooBar2 overrides Equals(IFoo other), but that's not what gets called on ==. I'm hunting through my code to replace a==b with a.Equals(b) everywhere, but that's just not nice.

What can I do?

like image 815
TDaver Avatar asked Feb 21 '11 13:02

TDaver


People also ask

Which operator Cannot overload?

Dot (.) operator can't be overloaded, so it will generate an error.

Which operator can be overload?

The two member access operators, operator->() and operator->*() can be overloaded. The most common use of overloading these operators is with defining expression template classes, which is not a common programming technique.

Can interface contain operators?

You can't define operators on interfaces because a class can implement multiple interfaces.

Can we overload address of operator?

You cannot overload the following operators: . You cannot overload the preprocessor symbols # and ## . An operator function can be either a nonstatic member function, or a nonmember function with at least one parameter that has class, reference to class, enumeration, or reference to enumeration type.


1 Answers

No, you can't. Overloading == requires static methods in one of the types you use, and an interface can't contain those. Extension methods can't help either. So on interfaces == is always using reference equality.

Note that a.Equals(b) will throw an exception if a==null.

like image 105
CodesInChaos Avatar answered Sep 21 '22 23:09

CodesInChaos