Understanding Class Interfaces
By convention, interfaces are named starting with a capital I with the subsequent letter also capitalized.
(Another example besides IComparable is IEnumerable.)
An interface is like an abstract base class: both do not spell out implementation details and are used by
derived classes. However, a class can derive from a base class and can also implement an interface—or, in
fact, implement multiple interfaces. (In contrast, C# classes can only inherit from one base class.) In
this respect, interfaces are more general—and arguably more useful—than class inheritance.
Interface implementations help to ensure consistency. Studies have shown that software written with class
libraries that implement interfaces tends to have fewer defects.
Interfaces work well in situations in which one set of programmers has created a class library (for example,
the creators of the .NET Framework) and another set will be using the classes (you and me). Interface
implementation also provides a good way for a team leader to deliver project specifications: the project
lead writes the interfaces, and specifies mandatory implementation within classes.
As I’ll show you later in this article, the Visual Studio .NET development environment itself helps to
enforce the contract created by an interface. If you attempt to run a project containing a class that
implements an interface, and the members specified by the interface are not implemented in the class,
you’ll get syntax errors (and the project containing the code will neither run nor compile).
|