Codiqo

Learn C# · lesson 45 of 61 · about 10 minutes

Project: The Dragon Hunt

Send the guild after the dragon: model adventurers with an abstract class, then sort and sum them polymorphically.

What you'll learn

  • Write an abstract class with abstract members
  • Validate in constructors
  • Use LINQ on a list of base types

The dragon hunt

The guild goes after the dragon, which has 60 HP in the bestiary. Every guild member joins as a Knight (with 100 XP or more) or an Archer. Both are adventurers with a name and XP, but each works out its power differently: a Knight has 20 plus a tenth of their XP, and an Archer 10 plus a fifth. So Adventurer is an abstract class: it holds the name and XP, refuses negative XP in its constructor, and says every adventurer must have a Role and a Power(), without saying how. The party is listed from strongest to weakest, and if their power adds up to the dragon's HP or more, the dragon is slain.

The design

abstract class Shape can't be created directly; it says every shape must have Area and Perimeter:

public abstract double Area { get; }

Circle, Rectangle and Triangle override them. Constructors throw ArgumentException for sizes of 0 or less. Shape's own ToString uses GetType().Name and the overridden members, so it works for every shape.

One abstract member, one shape

Shape s = new Square(3);
Console.WriteLine(s.Area);

abstract class Shape
{
    public abstract double Area { get; }
}

class Square : Shape
{
    private readonly double _side;
    public Square(double side) => _side = side;
    public override double Area => _side * _side;
}

Output

9

The shapes

A constructor that throws means a bad object is never made, so everything in the list is valid. OrderBy and Sum work on the list of the abstract type, and each shape's own Area is used.

Shapes

List<Shape> shapes = new() { new Circle(1.5), new Rectangle(4, 2.5), new Triangle(3, 4, 5) };
try
{
    shapes.Add(new Rectangle(-1, 2));
}
catch (ArgumentException e)
{
    Console.WriteLine($"Skipped: {e.Message}");
}

foreach (Shape s in shapes.OrderBy(s => s.Area)) Console.WriteLine(s);
Console.WriteLine($"Total area {shapes.Sum(s => s.Area):F2}");

abstract class Shape
{
    public abstract double Area { get; }
    public abstract double Perimeter { get; }
    protected static double Check(double size) =>
        size > 0 ? size : throw new ArgumentException($"size must be positive, got {size}");
    public override string ToString() => $"{GetType().Name,-10} area {Area,6:F2}  perimeter {Perimeter,6:F2}";
}

class Circle : Shape
{
    private readonly double _r;
    public Circle(double r) => _r = Check(r);
    public override double Area => Math.PI * _r * _r;
    public override double Perimeter => 2 * Math.PI * _r;
}

class Rectangle : Shape
{
    private readonly double _w, _h;
    public Rectangle(double w, double h) { _w = Check(w); _h = Check(h); }
    public override double Area => _w * _h;
    public override double Perimeter => 2 * (_w + _h);
}

class Triangle : Shape
{
    private readonly double _a, _b, _c;
    public Triangle(double a, double b, double c) { _a = Check(a); _b = Check(b); _c = Check(c); }
    public override double Perimeter => _a + _b + _c;
    public override double Area
    {
        get
        {
            double s = Perimeter / 2;
            return Math.Sqrt(s * (s - _a) * (s - _b) * (s - _c));
        }
    }
}

Output

Skipped: size must be positive, got -1
Triangle   area   6.00  perimeter  12.00
Circle     area   7.07  perimeter   9.42
Rectangle  area  10.00  perimeter  13.00
Total area 23.07

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.