Explicit Interface Implementation purpose

P

puzzlecracker

I don't see the purpose of explicit interface implementation other
than to hide its signature in the class that implements it, and,
instead, write your own, perhaps with a different signature,
implementation. Also, if you implement more than two interfaces with
the same method, which is rarity in practice or so it seems. To me
it appears a shallow end... Am I missing something?


Thanks
 
M

Marc Gravell

Some interfaces are not intended for the programmer to call, or would
add clutter most of the time (called rarely). For example, ITypedList/
IBindingList/ICustomTypeDescriptor are examples from
System.ComponentModel that are intended for use by TypeDescriptor
(etc). You wouldn't call these methods directly, so why have them on
the API?

Sometimes explicit implementation is used to provide a more meaningful
public API - for example:

public Foo Clone() { ... } // always actually returns a Foo
object ICloneable.Clone() { return Clone(); }

The same is true of the non-generic IList etc.

And sometimes you need to do this because 2 interfaces have
conflicting methods, or the *interface* meaning of SomeMethod(), and
the class's *local* meaning of SomeMethod(), are slightly different.
IEnumerable<T>.GetEnumerator() is an example of the first.

Marc
 
A

Adam Benson

If an implementation is virtual and a base object has been derived several
times by others it can be hard to figure out exactly where the call goes.
With an explicit implementation the call always hits the call in the base
class - makes it easier to debug.

This approach has saved me a load of time with remoted calls.

ie.

interface I
{
void MyCall();
}

Derived6: Derived5
{
}

Derived5:Derived4
{
override void MyCall()
{
// Do stuff
base.MyCall();
}
}

Derived1:Base
{
override void MyCall()
{
// Do stuff
}
}

....

Base : I
{
virtual void MyCall()
{
}

I.MyCall()
{
// Always gets trapped here
this.MyCall(); // If you just called MyCall without explicit
implementation you'd have to hunt through every class that derives from Base
to find where a call to MyCall actually ends up.
}
}

Cheers,

Adam.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top