Chapter 14: Interfaces

1. What is an Interface? (Super Simple Analogy)

Think of an interface like a contract or a remote control standard:

  • The interface says: “If you want to be a part of my club, you must have these buttons/methods: Play(), Stop(), Pause()”
  • Any device that implements this interface (TV, Music Player, DVD Player, Game Console) must provide its own version of Play(), Stop(), Pause()
  • You can use any of these devices with the same remote (same code) – because they all follow the same contract

Key points:

  • Interfaces define WHAT a class must do (methods, properties, events)
  • They do NOT say HOW to do it – no implementation (except default methods in C# 8+)
  • Classes can implement multiple interfaces → this is C#’s way of doing multiple inheritance (safely!)

2. Defining an Interface

Syntax:

C#

Naming convention (very important):

  • Interface names start with I (capital i) → INotification, IRepository, ILogger

Real example – Notification contract

C#

3. Implementing an Interface

Any class that implements the interface must provide all the members!

C#

Polymorphic usage – same code for all notifiers

C#

Output:

text

4. Multiple Inheritance via Interfaces (C#’s Superpower!)

Unlike classes (you can inherit only one base class), a class can implement many interfaces!

C#

Usage:

C#

5. Default Interface Methods (C# 8.0+) – Huge Game-Changer!

Since C# 8, interfaces can have default implementations – like a base method that children can use or override.

C#

Usage:

C#

Mini-Project: Payment Gateway System with Interfaces

C#

Summary – What We Learned Today

  • Interface = contract that defines what methods/properties a class must have
  • Classes implement interfaces with :
  • Multiple inheritance → implement many interfaces
  • Default methods (C# 8+) → provide default behavior
  • Polymorphism → treat different classes the same way via interface reference
  • Interfaces are everywhere in real .NET: IEnumerable<T>, IDisposable, ILogger<T>, IRepository, etc.

Your Homework (Super Practical!)

  1. Create a new console project called InterfaceMaster
  2. Create these interfaces:
    • IVehicle → Start(), Stop(), GetFuelLevel()
    • IElectric → ChargeBattery()
    • IGasoline → Refuel()
  3. Create classes:
    • ElectricCar : IVehicle, IElectric
    • GasCar : IVehicle, IGasoline
    • HybridCar : IVehicle, IElectric, IGasoline
  4. In Program.cs: Create a list of IVehicle, loop through them, start each, and charge/refuel where possible

Next lesson: Generics – we’re going to learn how to write super reusable, type-safe code that works with any data type!

You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with default methods or multiple interfaces? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *