← C# from Scratch Lesson 35 of 39 · 10 XP

Interfaces

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An interface is a list of what a class promises to be able to do, without the implementation:

interface IDamageable
{
    int Hp { get; }
    void TakeDamage(int amount);
}

interface IHealable
{
    void Heal(int amount);
}

class Player : IDamageable, IHealable      // a class can implement any number of interfaces
{
    public int Hp { get; private set; } = 100;
    public void TakeDamage(int amount) => Hp -= amount;
    public void Heal(int amount) => Hp += amount;
}

class Barrel : IDamageable { … }           // a barrel can be broken too, but not healed
  • interface names customarily start with I;
  • a method that takes an IDamageable works with both the player and the barrel — it doesn't care which one it is;
  • to check whether an object can do something: if (obj is IHealable h) h.Heal(10);
  • an abstract class says "who you are" (one family); an interface says "what you can do" (different families can share a skill).

Task. Finish Player (HP 100, implements IDamageable and IHealable, healing no higher than 100) and Barrel (HP 30, only IDamageable). HP never goes below 0. The program applies commands such as hit player 20, heal barrel 10 and so on, printing not allowed when something can't be healed.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.