I have some code like this:
How should I implement the operator == so that it will be called when the variables are of interface IMyClass?
public class MyClass : IMyClass
{
public static bool operator ==(MyClass a, MyClass b)
{
if (ReferenceEquals(a, b))
return true;
if ((Object)a == null || (Object)b == null)
return false;
return false;
}
public static bool operator !=(MyClass a, MyClass b)
{
return !(a == b);
}
}
class Program
{
static void Main(string[] args)
{
IMyClass m1 = new MyClass();
IMyClass m2 = new MyClass();
MyClass m3 = new MyClass();
MyClass m4 = new MyClass();
Console.WriteLine(m1 == m2); // does not go into custom == function. why not?
Console.WriteLine(m3 == m4); // DOES go into custom == function
}
}
The key is that you’re not overriding an operator – you’re overloading it.
There’s no operator defined for
so the compiler has nothing it could call. It can’t call
as it doesn’t know that
m1andm2will actually refer to instance ofMyClass.As far as I know there’s no way of implementing an operator to be used for interfaces – after all, multiple implementations could all provide their own one, just for one point of possible ambiguity.
Personally I’m somewhat wary of trying to talk about equality over non-sealed types to start with – equality and inheritance don’t mix terribly nicely. That goes doubly for interfaces, of course 🙂 You might be best implementing an appropriate
IEqualityComparer<IMyClass>and using that instead.