Interfaces and polymorphism
Interfaces are contracts that let many types plug into the same code.
- Define small interfaces that describe one capability.
- Program to the interface so behaviour can be swapped.
- Use composition to assemble features instead of building deep hierarchies.
In plain English
An interface is a contract of methods and properties a type promises to provide. A class or record implements the interface by writing those members. Polymorphism lets code depend on the interface and work with any implementation. Composition builds objects from smaller parts, and it is usually safer than deep inheritance. Prefer composition when the parts vary independently.
Step by step
- 1Declare an interface with one method.
- 2Implement it in two different records.
- 3Write a class that accepts the interface and calls it.
- 4Pass different implementations and watch the behaviour change.
public interface IPrintable
{
string Render();
}
public record Course(string Slug, string Title) : IPrintable
{
public string Render() => Title;
}
public record Lesson(string Title, int Minutes) : IPrintable
{
public string Render() => Title + " (" + Minutes + " min)";
}
public class Report
{
private readonly IPrintable[] items;
public Report(IPrintable[] items)
{
this.items = items;
}
public void Print()
{
foreach (var item in items)
{
Console.WriteLine(item.Render());
}
}
}
var report = new Report(new IPrintable[]
{
new Course("csharp", "C# Foundations"),
new Lesson("Variables", 12),
});
report.Print();Common mistakes
- Forgetting to implement an interface member causes a compile error.
- Adding a method to an interface breaks every existing implementer.
- Deep inheritance couples classes to ancestors they do not actually need.
- Composition keeps each piece small and independently changeable.
Implement a reportable item
Create an interface IPrintable with a string Render() method, then a record Lesson that implements it and returns its title.
public interface IPrintable
{
}What is polymorphism in C#?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.