Why implement interface explicitly?

If you implement two interfaces, both with the same method and different implementations, then you have to implement explicitly.

public interface IDoItFast
{
    void Go();
}
public interface IDoItSlow
{
    void Go();
}
public class JustDoIt : IDoItFast, IDoItSlow
{
    void IDoItFast.Go()
    {
    }

    void IDoItSlow.Go()
    {
    }
}

It's useful to hide the non-preferred member. For instance, if you implement both IComparable<T> and IComparable it is usually nicer to hide the IComparable overload to not give people the impression that you can compare objects of different types. Similarly, some interfaces are not CLS-compliant, like IConvertible, so if you don't explicitly implement the interface, end users of languages that require CLS compliance cannot use your object. (Which would be very disastrous if the BCL implementers did not hide the IConvertible members of the primitives :))

Another interesting note is that normally using such a construct means that struct that explicitly implement an interface can only invoke them by boxing to the interface type. You can get around this by using generic constraints::

void SomeMethod<T>(T obj) where T:IConvertible

Will not box an int when you pass one to it.

Tags:

C#

Interface