C Sharp

Interfaces

The key to understanding interfaces might be to compare them with classes. Classes are objects that have properties and methods that act on those properties. While classes do exhibit some behavioral characteristics (methods), classes are things as opposed to behaviors, and that's how interfaces come in. Interfaces enable you to define behavioral characteristics, or abilities, and apply those behaviors to classes irrespective of the class hierarchy.

For example, say that you have a distribution application in which some of the entities can be serialized. These might include the Customer, Supplier and Invoice classes. Some other classes, such as MaintenanceView and Document,might not be defined as serializable. How would you make only the classes you choose serializable? One obvious way would be to create a base class called something like Serializable. However, that approach has a major drawback. A single inheritance path won't work because we don't want all the behaviors of the class to be shared. C# doesn't support multiple inheritance, so there's no way to have a given class selectively derive from multiple classes. The answer is interfaces. Interfaces give you the ability to define a set of semantically related methods and properties that selected classes can implement regardless of the class hierarchy.

From a conceptual standpoint, interfaces are contracts between two disparate pieces of code. That is, once an interface is defined and a class is defined as implementing that interface, clients of the class are guaranteed that the class has implemented all methods defined in the interface. You'll see this soon in some examples.

In this chapter, we'll look at why interfaces are such an important part of C# and component-based programming in general. Then we'll take a look at how to declare and implement interfaces in a C# application. Finally, we'll delve into more of the specifics regarding using interfaces and overcoming the inherent problems with multiple inheritance and name collision.

NOTE


When you define an interface and specify that a class is going to make use of that interface in its definition, the class is said to be implementing the interface or inheriting from the interface. You can use both phrases, and you'll see them used interchangeably in other texts. Personally, I believe that implement is the more semantically correct term—interfaces are defined behaviors and a class is defined as implementing that behavior, as opposed to inheriting from another class—but both terms are correct.