views:

193

answers:

2

If an interface inherits IEquatable the implementing class can define the behavior of the Equals method. Is it possible to define the behavior of == operations?

public interface IFoo : IEquatable  
{}  

public class Foo : IFoo  
{  
    // IEquatable.Equals  
    public bool Equals(IFoo other)  
    {  
        // Compare by value here...
    }  
}

To check that two IFoo references are equal by comparing their values:

IFoo X = new Foo();  
IFoo Y = new Foo();

if (X.Equals(Y))  
{  
     // Do something  
}

Is it possible to make if (X == Y) use the Equals method on Foo?

+4  A: 

No - you can't specify operators in interfaces (mostly because operators are static). The compiler determines which overload of == to call based purely on their static type (i.e. polymorphism isn't involved) and interfaces can't specify the code to say "return the result of calling X.Equals(Y)".

Jon Skeet
And this is the thing I miss the most when using generics, oh... and specialization.
Coincoin
A: 

No, because interface can't contain operator functions. A solution would be to make IFoo an abstract class instead of an interface :

abstract class IFoo : IEquatable<IFoo> 
{
    public static bool operator ==(IFoo i1, IFoo i2) { return i1.Equals(i2); }
    public static bool operator !=(IFoo i1, IFoo i2) { return !i1.Equals(i2); }
    public abstract bool Equals(IFoo other);
}

class Foo : IFoo
{
    public override bool Equals(IFoo other)
    {
        // Compare
    }
}

Of course, this makes you lose the flexibility provided by interfaces.

Luc Touraille