Problem
What are the differences between implicit and explicit interface implementation in C#?
When is it appropriate to use implicit and when is it appropriate to use explicit?
Are there any advantages and/or disadvantages to one or the other?
Using explicit implementations is not advised, according to Microsoft’s official recommendations (from the first edition Framework Design Guidelines), because it causes unexpected behavior in the code.
This rule, in my opinion, is highly true in the pre-IoC era, when things aren’t passed around via interfaces.
Could somebody comment on that as well?
Asked by Seb Nilsson
Solution #1
When you specify your interface using a class member, it’s called implicit. When you define methods within your class on the interface, it’s called explicit. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
Implicit implementation, on the other hand, allows you to access the interface through the class you constructed by casting the interface as both that class and the interface itself. You can only access the interface by casting it as the interface itself with explicit implementation.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
Explicit is used largely to keep the implementation clean or when two implementations are required. Regardless, I don’t use it very often.
Others will undoubtedly provide other reasons to use or not utilize explicit.
For good reasons for each, see the following post in this thread.
Answered by mattlant
Solution #2
The implicit definition would be to simply add the interface-required methods / properties, etc. to the class as public methods.
When working with the interface directly rather than the underlying implementation, explicit definition causes the members to be exposed only when working with the interface. In most circumstances, this is the best option.
Answered by Phil Bennett
Solution #3
There are several circumstances when detailed implementation is REQUIRED for the compiler to figure out what is required, in addition to the good solutions already supplied. Take a look at IEnumerableT> as an example that will most likely be used frequently.
Here’s an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Because IEnumerablestring> implements IEnumerable, we must as well. But wait, both the generic and the regular versions implement functions with the same method signature (the return type in C# is ignored in this case). This is perfectly legal and acceptable. What method does the compiler use to decide which to use? It forces you to have only one implicit definition at the most, after which it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The indirection in the explicit definition for IEnumerable works because the compiler understands that the variable’s actual type is a StringList inside the method, and that’s how it resolves the function call. A useful tidbit for implementing some of the layers of abstraction that the.NET core interfaces appear to have amassed.
Answered by Matthew Scharley
Solution #4
To quote CLR via CJeffrey #’s Richter: (EIMI means Explicit Interface Method Implementation)
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That isn’t polymorphism at all.
EIMIs can also be used to hide non-strongly typed interface members from fundamental Framework Interface implementations like IEnumerableT>, ensuring that your class does not directly expose a non-strongly typed method while remaining syntactically correct.
Answered by Valentin Kuzub
Solution #5
When I wish to avoid “programming to an implementation,” I usually use explicit interface implementation (Design Principles from Design Patterns).
In an MVP-based web application, for example:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Another class (such as a presenter) is now more likely to rely on the INavigator interface than to the StandardNavigator implementation (since the implementation would need to be cast to an interface to make use of the Redirect method).
Another reason I would use an explicit interface implementation is to keep the “default” interface of a class tidy. If I were creating an ASP.NET server control, for example, I may want two interfaces:
Here’s a simple example. It’s a customer-listing combo box control. The web page developer in this case isn’t interested in filling the list; instead, they want to be able to choose a client by GUID or acquire the GUID of the selected customer. On the first page load, a presenter would populate the box, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The data source is filled by the presenter, and the web page creator is never aware of its presence.
I wouldn’t recommend using explicit interface implementations all of the time. These are just two scenarios in which they could be beneficial.
Answered by Jon Nadal
Post is based on https://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation