Skip to content
Codewilds

Lesson 26 of 34 · Inheritance & Interfaces

C# Interfaces: Contracts for Your Classes

medium20 XP3 min read

Abstract classes share code through a family tree. But many abilities cut across families: a barrel, a castle gate and a dragon can all be damaged, while only the gate can be repaired. An interface describes a capability — a contract of members that a class promises to provide — without saying anything about how, and without forcing the classes into one hierarchy.

Declaring an interface

public interface IDamageable
{
    int Health { get; }
    bool IsDestroyed { get; }
    void TakeDamage(int amount);
}

Interface names start with a capital I by convention. Members have no access modifier — they are public — and normally no body.

Implementing interfaces

A class implements an interface by listing it after a colon and providing every member:

public class Barrel : IDamageable
{
    public int Health { get; private set; } = 20;
    public bool IsDestroyed => Health == 0;

    public void TakeDamage(int amount) => Health = Math.Max(0, Health - amount);
}

A class can inherit from only one base class, but it can implement any number of interfaces, separated by commas — the base class (if any) comes first:

public class Gate : Structure, IDamageable, IRepairable { /* ... */ }

Programming against interfaces

The real benefit appears when code depends on the interface instead of a concrete class. This method works with barrels, gates and anything damageable that someone writes next year:

public static void Explode(List<IDamageable> targets)
{
    foreach (IDamageable target in targets)
    {
        target.TakeDamage(50);
    }
}

You cannot create an interface with new IDamageable(), but a variable of an interface type can hold any object that implements it.

Testing for a capability with is

The is operator with a type pattern checks whether an object implements an interface and gives you a typed variable in one step:

object thing = new Gate();
if (thing is IRepairable repairable)
{
    repairable.Repair(10);
}

Interfaces you already use

.NET is full of interfaces. List<T> implements IEnumerable<T>, which is what makes foreach work. IComparable<T> lets Sort() order your objects, and IDisposable marks objects that hold resources and works with the using statement. Since C# 8, interfaces may also contain default implementations, such as bool IsDestroyed => Health <= 0;, which implementing classes can keep or replace.

Interface or abstract class?

Use an abstract class when related classes share state and code (all shapes have a Describe() method built on Area()). Use an interface when unrelated classes share a capability (barrels and gates can both be damaged). Many designs use both.

Common mistakes

  • Missing a member: the compiler error "does not implement interface member" names it.
  • Making an implementing member non-public: interface members must be implemented as public (or explicitly).
  • Casting without checking: (IRepairable)thing throws when thing is a barrel — use is or as.

Assignment

The interfaces IDamageable and IRepairable are given. Complete the classes:

  1. Barrel starts with 20 health. TakeDamage lowers the health (never below 0) and IsDestroyed is true at 0 health.
  2. Gate starts with MaxHealth (100) health and has Armor 5: every hit is reduced by the armor (a hit of 30 does 25 damage, a hit of 3 does nothing). Repair(amount) heals but never above MaxHealth.
  3. Siege.Bombard(targets, damage) hits every target once and returns how many targets are destroyed afterwards.
  4. Siege.RepairAll(things, amount) repairs every object in the list that is IRepairable and returns how many were repaired.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Interfaces in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 26 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.