Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between implicit and explicit implementation of C# interfaces [duplicate]

Tags:

c#

interface

What's the difference between Explicitly implement the interface and Implement the interface.

When you derive a class from an interface, intellisense suggest you to do both.

But, what's the difference?

like image 222
eKek0 Avatar asked Apr 03 '09 05:04

eKek0


2 Answers

Another aspect of this:

If you implicitly implemented, it means that the interface members are accessible to users of your class without them having to cast it.

If it's explicitly implemented, clients will have to cast your class to the interface before being able to access the members. Here's an example of an explicit implementation:

    interface Animal
{
    void EatRoots();
    void EatLeaves();
}

interface Animal2
{
    void Sleep();
}


class Wombat : Animal, Animal2
{
    // Implicit implementation of Animal2
    public void Sleep()
    {
    }

    // Explicit implementation of Animal
    void Animal.EatRoots()
    {

    }

    void Animal.EatLeaves()
    {
    }

}

Your client code

Wombat w = new Wombat();
w.Sleep();
w.EatRoots();   // This will cause a compiler error because it's explicitly implemented
((Animal)w).EatRoots();  // This will compile
like image 128
Andrew Shepherd Avatar answered Oct 12 '22 00:10

Andrew Shepherd


The IDE gives you the option to do either - it would be unusual to do both. With explicit implementation, the members are not on the (primary) public API; this is handy if the interface isn't directly tied to the intent of the object. For example, the ICustomTypeDescriptor members aren't all that helpful to regular callers - only to some very specific code, so there is no purpose having them on the public API causing mess.

This is also useful if:

  • there is a conflict between an interface's Foo method and your own type's Foo method, and they mean different things
  • there is a signature conflict between other interfaces

The typical example of the last point is IEnumerable<T>, which has a GetEnumerator() method at two levels in the interface hierarchy - it is common to implement the typed (IEnumerator<T>) version using implicit implementation, and the untyped (IEnumerator) version using explicit implementation.

like image 23
Marc Gravell Avatar answered Oct 12 '22 00:10

Marc Gravell