What is explicit interface implementation, and why use it?

C# OOP Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

Explicit implementation — void IDisposable.Dispose() { } — makes the member accessible only through the interface, not on the class directly. Use it to resolve a name clash between two interfaces, to keep a rarely-needed interface method off the class's public surface, or to provide a different implementation per interface.

Normally when I implement an interface method, it's just a public method on the class. Explicit implementation writes it as void IFoo.Method(), and then it's only callable if you have a reference typed as IFoo — it doesn't show up on the class itself. I use it when two interfaces both declare a method with the same name and I need different behaviour for each, or to keep something like the non-generic IEnumerable.GetEnumerator off the public surface so it doesn't clutter autocomplete.

  • Implicit: the method is a normal public member and satisfies the interface.
  • Explicit: var x = new MyList(); x.Count — error; ((ICollection)x).Count — works.
  • Classic use: implementing both IEnumerable<T> and non-generic IEnumerable — the non-generic GetEnumerator is explicit so it doesn't clutter IntelliSense.
  • Can't mark explicit members with an access modifier (they're always “private-ish”).