Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the use of explicit interface implementation meant for hiding functionality?

Tags:

c#

interface

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?

like image 254
PRASHANT P Avatar asked May 25 '11 19:05

PRASHANT P


People also ask

What is the use of explicit 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.

Do interfaces hide information?

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".

What is the difference between implicit and explicit interface?

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.

What is implicit and explicit implementation of interface?

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.


1 Answers

There are two main uses for it in my experience:

  • It allows you to overload methods by return value. For example, 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.
  • It allows you to implement part of an interface in a "discouraging" way - for example, 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.
like image 94
Jon Skeet Avatar answered Sep 25 '22 04:09

Jon Skeet