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?
It is not meant for hiding methods but to make it possible to implement two methods with the same signature/name from different interface in to different ways.
If both IA and IB have the operation F you can only implement a different method for each F by explicitly implementing the interfaces.
There are two main uses for it in my experience:
IEnumerable<T>
andIEnumerable
both declareGetEnumerator()
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>
implementsIList<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.One example is ICloneable. By implementing it explicitly, you can have still have a strongly typed version:
It can be used for hiding. For example, some classess that implement
IDisposable
do so explicitly because they also have aClose()
method which does the same thing.You can also use the explicit interface definitions for when you are implementing two interfaces on one class and there is a signature clash and the functionality differs depending on the interface. However, if that happens it is usually a sign that your class is doing too much and you should look at splitting the functionality out a bit.