Sometimes several types are all versions of one idea: a timed task and a reading task are both tasks. Inheritance lets a class start from another class, gaining its members and adding or changing some of them. The original is the base class, and the new one is the derived class.
Deriving a class
: Item means "derives from Item". A derived class's constructor passes values up with : base(...). Both kinds of object below can be stored in a List<Item>, because each of them is an Item.
var items = new List<Item>
{
new Item("Notebook"),
new Book("Dune", 412),
};
foreach (Item item in items)
{
Console.WriteLine(item.Name);
}
class Item
{
public string Name { get; }
public Item(string name)
{
Name = name;
}
}
class Book : Item
{
public int Pages { get; }
public Book(string name, int pages) : base(name)
{
Pages = pages;
}
}Check your prediction
Notebook
Dunevirtual and override
To let a derived class replace a method, the base class marks it virtual, and the derived class marks its version override. The version that runs depends on the object's actual type, not on the type of the variable. That behaviour is called polymorphism, and it's what makes inheritance useful.
Item plain = new Item("Notebook");
Item book = new Book("Dune", 412);
Console.WriteLine(plain.Describe());
Console.WriteLine(book.Describe());
class Item
{
public string Name { get; }
public Item(string name)
{
Name = name;
}
public virtual string Describe() => Name;
}
class Book : Item
{
public int Pages { get; }
public Book(string name, int pages) : base(name)
{
Pages = pages;
}
public override string Describe() => $"{base.Describe()} ({Pages} pages)";
}Check your prediction
Notebook
Dune (412 pages)book is declared as Item, yet Book's method runs. base.Describe() calls the version being replaced, so Book only adds what's new.
Fix it: the override that wasn't
This is one of the most common inheritance bugs. Someone writes the derived method but forgets override. Predict both lines, then run it and read the compiler's message.
Item book = new Book("Dune", 412);
Book sameBook = (Book)book;
Console.WriteLine(book.Describe());
Console.WriteLine(sameBook.Describe());
class Item
{
public string Name { get; }
public Item(string name)
{
Name = name;
}
public virtual string Describe() => Name;
}
class Book : Item
{
public int Pages { get; }
public Book(string name, int pages) : base(name)
{
Pages = pages;
}
public string Describe() => $"{Name} ({Pages} pages)";
}Check your prediction
It prints Dune and then Dune (412 pages), and the compiler warns:
warning CS0114: 'Book.Describe()' hides inherited member 'Item.Describe()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.The same object describes itself differently depending on the variable's type. Without override, Book.Describe is a separate method that merely has the same name. It hides the base one, so it runs only when the variable's type is Book. Code that holds an Item, such as a List<Item>, never sees it. Fix the program so both lines describe the book fully.
Fix it
Add override to Book.Describe:
Item book = new Book("Dune", 412);
Book sameBook = (Book)book;
Console.WriteLine(book.Describe());
Console.WriteLine(sameBook.Describe());
class Item
{
public string Name { get; }
public Item(string name)
{
Name = name;
}
public virtual string Describe() => Name;
}
class Book : Item
{
public int Pages { get; }
public Book(string name, int pages) : base(name)
{
Pages = pages;
}
public override string Describe() => $"{Name} ({Pages} pages)";
}Dune (412 pages)
Dune (412 pages)The warning's other suggestion, the new keyword, means "I'm hiding this on purpose". It silences the warning but keeps the two answers, so it's almost never what you want. If the base method isn't virtual at all, you get the similar warning CS0108, and the fix is to make it virtual in the base class first. Treat both warnings as errors.
abstract: a promise without a body
Some base classes don't make sense as objects on their own. What would a plain "shape" look like? An abstract class can't be created directly, and an abstract method has no body, so every non-abstract derived class must supply one. The compiler enforces that.
var shapes = new List<Shape> { new Square(2), new Rectangle(2, 3) };
foreach (Shape shape in shapes)
{
Console.WriteLine(shape.Summary());
}
abstract class Shape
{
public abstract double Area();
public string Summary() => $"{GetType().Name}: {Area()}";
}
class Rectangle : Shape
{
private readonly double width;
private readonly double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public override double Area() => width * height;
}
sealed class Square : Rectangle
{
public Square(double side) : base(side, side)
{
}
}Check your prediction
Square: 4
Rectangle: 6Summary is ordinary shared code that calls an abstract method. sealed stops anything deriving from Square. Seal classes unless you've designed them to be derived from; overriding is hard to get right by accident.
Records can inherit too
A record can derive from another record, and its ToString and equality include the extra fields. The task tracker uses this shape for its Result type on Day 4.
Event first = new Login("ana");
Event second = new Login("ana");
Console.WriteLine(first);
Console.WriteLine(first == second);
abstract record Event;
sealed record Login(string User) : Event;Check your prediction
Login { User = ana }
TrueWhen not to inherit
Ask "is a B truly a kind of A, everywhere an A is used?" A Book is an Item. A Stack isn't a kind of List, even though it could reuse one, because a list allows inserting in the middle and a stack shouldn't. Hold the list in a private field instead. Tomorrow's lessons use that style, called composition, far more often than inheritance.
Your turn
Pay by kind of worker
Write an abstract class Worker with a Name, an abstract method decimal Pay(), and a method Slip() that returns text such as Ana: 3000. Derive Salaried, which has a monthly amount, and Hourly, which has hours and a rate. Print slips for Ana on 3000 a month and Ben on 100 hours at 12.50.
When it works, it prints:
Ana: 3000
Ben: 1250.00Console.WriteLine("Start here");Hint 1: the idea
Slip belongs in the base class because it's the same for everyone. Only Pay differs, so that's the abstract part.
Hint 2: a first step
Write the abstract class with its constructor and Slip, then write Salaried alone. The compiler tells you when a required method is missing.
Show one solution
var staff = new List<Worker> { new Salaried("Ana", 3000m), new Hourly("Ben", 100, 12.50m) };
foreach (Worker worker in staff)
{
Console.WriteLine(worker.Slip());
}
abstract class Worker
{
public string Name { get; }
protected Worker(string name)
{
Name = name;
}
public abstract decimal Pay();
public string Slip() => $"{Name}: {Pay()}";
}
sealed class Salaried : Worker
{
private readonly decimal monthly;
public Salaried(string name, decimal monthly) : base(name)
{
this.monthly = monthly;
}
public override decimal Pay() => monthly;
}
sealed class Hourly : Worker
{
private readonly int hours;
private readonly decimal rate;
public Hourly(string name, int hours, decimal rate) : base(name)
{
this.hours = hours;
this.rate = rate;
}
public override decimal Pay() => hours * rate;
}Ana: 3000
Ben: 1250.00Pay is abstract because there's no sensible pay for a worker of no particular kind, and the compiler then makes sure that every kind supplies one. Slip is written once in the base class and calls Pay, so adding a third kind of worker means writing one new class and no changes to the loop. The base constructor is protected, since only derived classes should call it.
Notice 1250.00: a decimal keeps the two decimal places of 12.50m. protected means "visible here and in derived classes", which suits a constructor that only derived classes should call.
Completion is saved in this browser only. It does not measure mastery.