Join Joe Marini for an in-depth discussion in this video Understanding interfaces in C#, part of C#: Interfaces and Generics.
- We'll get into more detail about interfaces later in the course. But for now, let's take a high-level conceptual overview of what interfaces are, and why they are used. In C# you use classes to create objects. To define different kinds of objects, you create different class definitions. In this example, I have three different classes, and each can have its own properties and methods relaying information. Interfaces are different from classes in a number of important ways. They describe behavior instead of discrete objects.
When an object implements an interface, it is basically saying to the rest of the program, "This object knows how to perform this behavior." So, if I wanted different types of objects in my app to have a particular capability, like, for example, being able to encrypt their data, or being able to broadcast an event when the object's data changes, I could create an interface for that behavior, and then each object would implement that interface. Another class can then make use of those capabilities on that object, without having to know much about what type of object it is.
All the caller needs to know is what interfaces are available. In this way you can think of an interface as a kind of contract. When you have a reference to an object that implements an interface, you know that that object can perform whatever functions that interface specifies. Later in the interfaces chapter, we'll see how to do this in greater detail, and work in example code. For now though, here are some important things to keep in mind about C# interfaces. First, interfaces describe behavior, not individual objects.
Second, a single interface can be used by many different classes. It is not necessarily tied to just one class. Third, a C# class can only inherit from one parent class, but can implement multiple interfaces. We'll also see this later on. Fourth, interfaces don't actually provide any implementation logic themselves. They simply indicate that an object can perform a certain function. It is up to the object's class itself to implement the behavior. That should give you a good introduction to the concept of interfaces, which we'll see more of later in the course.
Next, we'll take a look at generics, another important feature of C#, and then we'll dive into the details of each section.
Released
9/17/2015- 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
Share this video
Embed this video
Video: Understanding interfaces in C#