×

c# · level 2 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a promise a class can keep.

An interface is a promise. interface IPayment { string Pay(decimal amount); } lists what a class must be able to do, with no bodies at all. Interface names start with a capital I by habit.

A class that writes every method an interface lists can it: class Card : IPayment. Card and Cash share no base class, yet one array of IPayment holds both, and each pays its own way. A class may implement several interfaces, separated by commas.

Leave out a promised method and C# refuses with CS0535.

using System;

IPayment[] payments = { new Card(), new Cash() };
foreach (IPayment p in payments)
{
    Console.WriteLine(p.Pay(12.50m));
}

interface IPayment
{
    string Pay(decimal amount);
}
class Card : IPayment
{
    public string Pay(decimal amount) { return $"Tapped a card for {amount}"; }
}
class Cash : IPayment
{
    public string Pay(decimal amount) { return $"Handed over {amount} in coins"; }
}

A class can have one base class but implement many interfaces.