Home > Back-end >  Interfaces providing default Interface Implementation
Interfaces providing default Interface Implementation

Time:10-11

If I have:

public interface IValueStorage : IComparable<IValueStorage>
{
    public int compareObject {get;}
    public int CompareTo(IValueStorage other)
    {
        return compareObject.CompareTo(other.compareObject);
    }
}

Why do I need to redefine the interface implementation of IComparable on any classes that implement this interface? Can I declare each member use the base implementation?

I would ordinarily just change this interface to an abstract class, but on this occasion, the implementers of this interface are all (and should remain) structs.

CodePudding user response:

IService.CompareTo does not override IComparable<IService>.CompareTo; it creates a new method that your structs must implement. In order to have an interface method override another interface's method, you must use the explicit interface implementation syntax:

public interface IService : IComparable<IService>
{
    public int compareObject { get; }
    int IComparable<IService>.CompareTo(IService other)
    {
        return compareObject.CompareTo(other.compareObject);
    }
}

CodePudding user response:

What you actually do in your case, is declaring a new CompareTo method, which has nothing to do with the same-named method declared in IComparable<T>. In other words, the following code:

public interface IService : IComparable<IService>
{
    public int CompareTo(IService other)
    {
        …
    }
}

is not a default implementation of int IComparable<IService>.CompareTo(IService), but a standalone declaration of a new int CompareTo(IService) method.

Hence in the class implementing IService, there will be two implementations of CompareTo, one for each interface IService and IComparable<IService>.

As Joe Sewell pointed out in his answer, you can use the explicit implementation syntax in the derived interface:

int IComparable<IService>.CompareTo(IService other)
{
    …
}
  •  Tags:  
  • c#
  • Related