Is using an explicit interface implementation to hide functionality?

I use interfaces to decouple the code. I am curious if using an explicit interface implementation is intended to hide functionality?

Example:

public class MyClass : IInterface { void IInterface.NoneWillCall(int ragh) { } } 

What advantage and specific use case for this method can be obtained only through the interface?

+7
source share
4 answers

In my experience there are two main uses:

  • This allows you to overload methods by return value. For example, IEnumerable<T> and IEnumerable declare GetEnumerator() methods, but with different return types - therefore, to implement both, you must 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 more specific) with one of the interface method.
  • This allows you to implement part of the interface in a "discouraging" way - for example, ReadOnlyCollection<T> implements IList<T> , but "scares off" mutating calls using an explicit interface implementation. This will prevent callers who know about the object by its specific type from calling the wrong methods. It smells a bit like interfaces that are too wide or inappropriately implemented. Why would you implement an interface if you were unable to fulfill all of its contracts? - but in a pragmatic sense, this can be useful.
+11
source

One example is ICloneable . By implementing it explicitly, you can have a strongly typed version:

 public class MyClass : ICloneable { object ICloneable.Clone() { return this.Clone(); } public MyClass Clone() { return new MyClass() { ... }; } } 
+4
source

It is not intended to hide methods, but allows you to implement two methods with the same signature / name from different interfaces in different ways.

If both IA and IB have an operation F, you can implement a different method for each F by explicitly implementing the interfaces.

+2
source

It can be used to hide. For example, some classes that implement IDisposable do this explicitly because they also have a Close() method that does the same.

You can also use explicit interface definitions for cases where you implement two interfaces on the same class, and there is a collision with the signature, and the functionality differs depending on the interface. However, if this happens, this is usually a sign that your class is doing too much, and you should split the functionality a bit.

+2
source

All Articles