Chapter 13. Interfaces
There are times when you may not want to create a new type, but you do want to describe a set of behaviors that any number of types might implement. For example, you might want to describe what it means to be storable (capable of being written to disk) or printable.
Such a description is called an interface. An interface is a contract. When you design an interface, you’re saying “if you want to provide this capability, you must implement these methods, provide these properties and indexers, and support these events.” The implementer of the interface agrees to the contract and implements the required elements.
When specifying interfaces, it is easy to get confused about who is responsible for what. There are three concepts to keep clear:
- The interface
This is the contract. By convention, interface names begin with a capital I, so your interface might have a name such as
IPrintableinterface might require, among other things, a
Print( )method. This states that any class that wants to implement
IPrintablemust implement a
Print( )method, but it does not specify how that method works. That is up to the designer of the implementing class.
- The implementing class
This is the class that agrees to the contract described by the interface. For example,
Documentmight be a class that implements
IPrintableand thus ...