Learn C# · lesson 43 of 61 · about 9 minutes
Interfaces and Polymorphism
Make camp: describe what objects can do with interfaces, and treat different objects the same way.
What you'll learn
- Declare and implement an interface
- Use objects through an interface type
- Check types with is
Making camp
After the battle, the hero makes camp and uses what's in the bag. Bread heals 5 HP, rope is tied between two trees, and a torch adds 1 to the hero's power. Each thing is used differently, but camp doesn't need to know how: an IUsable interface says every usable thing has a Name and a Use(Fighter user) method. Bread, Rope and Torch each keep that promise in their own way, they all go into one List<IUsable>, and one loop calls u.Use(you) on each, so the bag's things are used in order and the hero's Fighter changes as they go.
Promises
An interface lists members a class promises to have. Names start with I:
interface IScorable { int Score(); }
class Quiz : IScorablemust then have a publicint Score()- A class has one parent class but can implement many interfaces
- Polymorphism: a
List<IScorable>can hold any mix of scorable things, and each runs its ownScore() if (x is Quiz q)checks the real type and gives you a typed variable
Keeping a promise
IWaver w = new Penguin();
Console.WriteLine(w.Wave());
interface IWaver { string Wave(); }
class Penguin : IWaver
{
public string Wave() => "Flap";
}Output
FlapOne list, many types
A variable or list of an interface type can hold any class that keeps the promise. Calling a member through it runs the real object's own version, and is checks what the object really is when you need to know.
Things that make noise
List<INoisy> things = new() { new Duck(), new Phone("ring ring"), new Duck() };
foreach (INoisy t in things) Console.Write(t.Noise() + " ");
Console.WriteLine();
foreach (INoisy t in things)
{
if (t is Phone p) Console.WriteLine($"Phone set to {p.Tone}");
}
interface INoisy
{
string Noise();
}
class Duck : INoisy
{
public string Noise() => "quack";
}
class Phone : INoisy
{
public string Tone { get; }
public Phone(string tone) => Tone = tone;
public string Noise() => Tone;
}Output
quack ring ring quack
Phone set to ring ringNow try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.