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?
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
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:
Foo
method and your own type's Foo
method, and they mean different thingsThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With