How does explicit interface implementation work, and when would you use it instead of a normal (implicit) implementation?
Short answer
Explicit implementation (`void IShape.Draw()`) makes the member ONLY accessible through a variable/reference TYPED AS THE INTERFACE, not directly on the concrete class instance — useful when a class implements TWO interfaces with a CONFLICTING member signature, or when you want…
Advertisement
AModel answer
Explicit implementation (`void IShape.Draw()`) makes the member ONLY accessible through a variable/reference TYPED AS THE INTERFACE, not directly on the concrete class instance — useful when a class implements TWO interfaces with a CONFLICTING member signature, or when you want to intentionally hide an interface member from the class's normal public surface.
public interface IEnglishGreeting { string Greet(); }
public interface ISpanishGreeting { string Greet(); }
public class Greeter : IEnglishGreeting, ISpanishGreeting {
string IEnglishGreeting.Greet() => "Hello";
string ISpanishGreeting.Greet() => "Hola";
}
Greeter g = new Greeter();
// g.Greet(); // Error: not accessible directly
string hello = ((IEnglishGreeting)g).Greet(); // must cast to access itReal-world example
Resolving a naming conflict when a class needs to implement two interfaces that happen to declare a method with the identical signature.
Likely follow-ups
- Why can't you simply implement BOTH interfaces' identically-named methods normally (implicitly) at the same time?
Related topics