c# · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Everyone says hello. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
IGreeter[] greeters = { new Robot(), new Parrot(), new Robot() };
foreach (IGreeter g in greeters)
{
Console.Write(g.Greet() + " ");
}
interface IGreeter
{
string Greet();
}
class Robot : IGreeter
{
public string Greet() { return "BEEP"; }
}
class Parrot : IGreeter
{
public string Greet() { return "Squawk"; }
}
your turn
Your turn. Wake up with a rooster.
On line 17, make Rooster implement IAlarm. On line 19, write the method the interface promises and choose the rooster's call. Press run.
output
press run to see what happens
fix it
The rain gauge broke its promise. Fix it!
output
press run to see what happens
- C# says
CS0535on line 17:RainGaugedoes not have the methodISensorpromises. - Compare the method name on line 19 with the one listed in the interface on line 11.
- Change
ReadingstoReadingon line 19, then press run.
nailed it
your classes keep their promises. :D
- An interface lists methods with no bodies.
class Card : IPaymentpromises to implement them all.- One array of an interface holds every class that keeps it.
new words in your collection
- interface
- implement
This lesson isn’t saved. A free account remembers every lesson you finish.