3.5 - Interfaces
Interfaces are a fundamental feature in C# that define a contract for classes to implement. An interface contains declarations of methods, properties, events, and indexers, but does not provide implementations. Classes that implement an interface must provide implementations for all the members defined in the interface.
🔰 Beginner's Corner: What is an Interface?
Think of an interface like a contract or a promise that a class makes:
┌───────────────────────────────────────────────────┐
│ │
│ INTERFACE AS A CONTRACT │
│ │
│ ┌─────────────────┐ │
│ │ Interface │ │
│ │ IVehicle │ │
│ │ │ │
│ │ • Start() │ │
│ │ • Stop() │◄────────┐ │
│ │ • Accelerate() │ │ │
│ └─────────────────┘ │ │
│ │ │
│ │ "I promise to │
│ │ implement all │
│ │ these methods" │
│ │ │
│ ┌─────────────────┐ │ │
│ │ Class │ │ │
│ │ Car ├─────────┘ │
│ │ │ │
│ │ • Start() {...} │ │
│ │ • Stop() {...} │ │
│ │ • Accelerate() {...} │
│ │ • Park() {...} │ │
│ └─────────────────┘ │
│ │
└───────────────────────────────────────────────────┘
💡 Concept Breakdown: Why Use Interfaces?
Interfaces solve several important problems in programming:
-
Define a contract - They specify exactly what methods and properties a class must implement
-
Enable polymorphism - They allow different classes to be treated the same way:
// These could be completely different classes
IVehicle car = new Car();
IVehicle boat = new Boat();
IVehicle plane = new Plane();
// But we can treat them the same way
vehicle.Start();
vehicle.Accelerate(); -
Support multiple inheritance - While a class can only inherit from one base class, it can implement many interfaces:
// A class can implement multiple interfaces
public class SmartPhone : IPhone, ICamera, IWebBrowser, IGPSDevice
{
// Must implement all members from all interfaces
}