Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement interface members explicitly or implicitly?

Tags:

c#

This question and Eric Lippert's answer got me wondering: How do you decide whether to use an explicit or implicit implementation when implementing methods of an interface?

like image 577
jasonh Avatar asked Dec 03 '09 18:12

jasonh


1 Answers

(personally) I only see a need for explicit implementations when there is a clash between methods with the same signature.

For example, when implementing IEnumerable<T>, you should implement 2 methods GetEnumerator() which have the same signature, except for the return type. So you'll have to implement IEnumerable.GetEnumerator() explicitly:

public abstract class MyClass<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {
        return ...;
    }

    IEnumerator IEnumerable.GetEnumerator() // explicit implementation required
    {
        return GetEnumerator();
    }
}

Another use for an explicit implementation is if you don't want the method to be called through an object instance, but only through an interface. I personally think this doesn't make much sense, but in some very rare cases, it can be useful.

like image 59
Philippe Leybaert Avatar answered Nov 03 '22 02:11

Philippe Leybaert