×

c# · level 2 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

lets one class build on another.

Dogs and cats are both animals: each has a name, and they all eat. Inheritance lets one class build on another, so you write the shared parts once. class Dog : Animal reads as “a Dog is an Animal”.

Animal is the class and Dog is the . A Dog inherits everything public in Animal, such as Name and Eat, and adds extras of its own, like Fetch.

Animal's constructor needs a name, so Dog's constructor passes one along: : base(name) runs the base constructor first. The word base always means the class you built on. Leave it out and C# refuses with CS7036.

using System;

var dog = new Dog("Rex");
dog.Eat();
dog.Fetch();

class Animal
{
    public string Name { get; set; }
    public Animal(string name) { Name = name; }
    public void Eat() { Console.WriteLine($"{Name} is eating."); }
}

class Dog : Animal
{
    public Dog(string name) : base(name) { }
    public void Fetch() { Console.WriteLine($"{Name} fetches the ball."); }
}

{ } is an empty body: the base constructor does all the work.