C# FoundationsยทC# from first file to first API

Interfaces and polymorphism

Interfaces are contracts that let many types plug into the same code.

Beginner 13 min read Lesson 3 of 300 Challenge included
What you will be able to do
  • 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

  1. 1Declare an interface with one method.
  2. 2Implement it in two different records.
  3. 3Write a class that accepts the interface and calls it.
  4. 4Pass different implementations and watch the behaviour change.
Shapes.csC#
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.
Your turn

Implement a reportable item

Medium

Create an interface IPrintable with a string Render() method, then a record Lesson that implements it and returns its title.

CSHARP ยท starter
public interface IPrintable
{
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What is polymorphism in C#?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: LINQ in depth
Lesson 3 of 300 ยท 0% of course