Join Joe Marini for an in-depth discussion in this video Understanding C# interfaces, part of C# Interfaces and Generics.
- View Offline
- Let's begin learning about C# interfaces by seeing how they're different from some other C# concepts. In particular classes, now as I mentioned earlier in the course, interfaces are different from classes in some important ways. A C# class describes an object. Classes are used as a kind of template mechanism to stamp out one or more of that kind of object. For example, you might create a class to represent the notion of a document. You can then use that class to create multiple document objects, each of which contain their own specific data.
Interfaces, on the other hand, are used to describe behavior. Interfaces are used by classes to tell other objects in a program that they can perform certain kinds of behavior. Classes can also implement more than one interface. in this example, suppose you wanted to give your documents the ability to store their data for later use. A behavior that's really useful for documents to have. In that case, you can define an interface named IStorable, and the letter I is a standard convention in C# for naming interfaces. Give it a couple of methods, like save and load, and then have your document class implement that interface.
The document class itself would then provide the actual programming logic for those methods, and then each document object would have that ability. Now, you might be wondering, why not just create a base class that contains methods for saving and loading, and then have the document class inherit from it? Well, you could do just that. But your application might have other objects that can also be stored. For example, what about a user's application preferences? Those can be stored too, but they clearly aren't documents. So it wouldn't make sense to have them inherit from the documents centric base class.
By using an interface, different kinds of objects can provide the same capabilities using the same set of define methods. Using interfaces gives you a way to separate out common sights of behavior in your application, and consume them in multiple places. How and when you might choose to use interfaces in your own applications will depend a lot on how your app is organized, and how complex it is. You might choose to just choose to use the built in C# interfaces, or you might choose to create some of your own. Just think of interfaces as another tool in your C# tool box that you can use to solve some of the programming scenarios that you might run into.
In the rest of this chapter, we'll take a look at how to define and implement interfaces. And then use our newly learned skills to complete a programming challenge involving interfaces.
- Designing and implementing an interface
- Implementing multiple interfaces
- Using .NET-defined interfaces
- Understanding how generics improve program reliability
- Exploring .NET's generic data collection classes