views:

80

answers:

3

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
    } 
}
+5  A: 

The key is that you're not overriding an operator - you're overloading it.

There's no operator defined for

operator ==(IMyClass x, IMyClass y)

so the compiler has nothing it could call. It can't call

operator ==(MyClass x, MyClass y)

as it doesn't know that m1 and m2 will actually refer to instance of MyClass.

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.

Jon Skeet
A: 

Try making the operator== function virtual.

apoorv020
It's static - and therefore can't be virtual. Operators aren't overridden, they're overloaded.
Jon Skeet
A: 

Look in the accepted answer for this question: http://stackoverflow.com/questions/112625/vs-object-equalsobject-in-net

The difference is one of identity equality vs semantic equality. Overriding == is meant for structs that are supposed to be the 'same' because they have the same values, since structs are copied by value and therefore are never references to the same object.

Equals is used for a semantic check of value equality for Reference types. By default, the two operations are the same.

Steve Mitcham