Chapter 13. Interfaces

Back in Chapter 11, you saw how inheritance and abstract methods can dictate the methods that a class has to implement. However, it isn’t always necessary to create a new parent class, even an abstract one, to guarantee the behaviors of your class. For example, you might want to dictate that your class must be storable (capable of being written to disk) or printable. “Storable” isn’t a good candidate for a class, because it doesn’t model an object; instead, it describes a set of behaviors that you want your class to have. Such a description is called an interface. The interface defines the methods that a class must implement, but it doesn’t dictate how the class implements these required methods. This provides a lot of flexibility on the part of the class designer, yet it allows client classes to use those methods with confidence, because the interface methods are guaranteed to be implemented. There are a lot of interesting things you can do with interfaces, including implementing multiple interfaces, combining them, inheriting them, and casting to them. All of it can be tricky to understand at first, so we’ll describe them all thoroughly in this chapter.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.