I use interfaces for decoupling my code. I am curious, is the usage of explicit interface implementation meant for hiding functionality?
Example:
public class MyClass : IInterface
{
void IInterface.NoneWillCall(int ragh) { }
}
What is the benefit and specific use case of making this available only explicitly via the interface?
Explicit interfaces are handy when either an object has two or more very distinct forms of communication. For example, an object that maintains a collection of child objects that need to communicate with parent.
Interfaces are not used to "hide" anything per se. It is used to establish a contract between the caller and the implementation. This contract promises that "these methods and properties will be here, and they will not change".
The main difference between explicit and implicit implementations is that implicit implementations must expose access to the member on the implementing concrete type. This means that the member will be available on the concrete type.
With implicit interface implementations, the members of the interface are public in the class. With explicit implementations, in the class the interface members are not declared as public members and cannot be directly accessed using an instance of the class, but a cast to the interface allows accessing the members.
There are two main uses for it in my experience:
IEnumerable<T>
and IEnumerable
both declare GetEnumerator()
methods, but with different return types - so to implement both, you have to implement at least one of them explicitly. Of course in this question both methods are provided by interfaces, but sometimes you just want to give a "normal" method with a different type (usually a more specific one) to the one from the interface method.ReadOnlyCollection<T>
implements IList<T>
, but "discourages" the mutating calls using explicit interface implementation. This will discourage callers who know about an object by its concrete type from calling inappropriate methods. This smells somewhat of interfaces being too broad, or inappropriately implemented - why would you implement an interface if you couldn't fulfil all its contracts? - but in a pragmatic sense, it can be useful.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