Chapter 8. Interfaces

An interface is a contract that guarantees to a client how a class or struct will behave. When a class implements an interface, it tells any potential client “I guarantee I’ll support the methods, properties, events, and indexers of the named interface.” (See Chapter 4 for information about methods and properties, see Chapter 12 for info about events, and see Chapter 9 for coverage of indexers.)

An interface offers an alternative to an abstract class for creating contracts among classes and their clients. These contracts are made manifest using the interface keyword, which declares a reference type that encapsulates the contract.

Syntactically, an interface is like a class that has only abstract methods. An abstract class serves as the base class for a family of derived classes, while interfaces are meant to be mixed in with other inheritance trees.

When a class implements an interface, it must implement all the methods of that interface; in effect the class says “I agree to fulfill the contract defined by this interface.”

Inheriting from an abstract class implements the is-a relationship, introduced in Chapter 5. Implementing an interface defines a different relationship, one we’ve not seen until now: the implements relationship. These two relationships are subtly different. A car is a vehicle, but it might implement the CanBeBoughtWithABigLoan capability (as can a house, for example).

Get Programming C# now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.