#451 – Implement Interface Explicitly to Simplify How a Class Appears to Clients

When you implement an interface explicitly, clients of the class can only see members of the interface if they access the object through the interface.

Assume that you have a Cow class which implements both the IMoo and the IStrangeCowBehavior interfaces.

public class Cow : IMoo, IStrangeCowBehavior

Also assume that the Cow class implements IStrangeCowBehavior explicitly, but implements IMoo normally.  Now a variable of type Cow will have access to the IMoo methods, but not the IStrangeCowBehavior methods.

If client code wants access to the IStrangeCowBehavior methods in Cow, it will need to access them via a variable of type IStrangeCowBehavior.

We’ve simplified things because most code that works with Cow objects won’t need access to the Burp, Dance, and DriveTractor methods and won’t even see the methods.  But code that needs these methods can get at them by using the appropriate interface variable.

Advertisement