Base classes, derived classes and base
Inheritance lets a class reuse and extend another. class Dog : Animal says a Dog is an Animal: it gets every public and protected member of Animal (the base class) and adds its own. C# allows one base class per class (single inheritance). A derived class's constructor must run a base constructor first; : base(...) chooses which one and what to pass.
var rex = new Dog("Rex", "beagle");
Console.WriteLine(rex.Describe());
rex.Eat();
rex.Fetch();
Animal a = rex; // a Dog IS an Animal
Console.WriteLine(a.Name);
class Animal
{
public string Name { get; }
protected int Meals; // visible to derived classes, not to callers
public Animal(string name) => Name = name;
public void Eat()
{
Meals++;
Console.WriteLine($"{Name} eats (meal {Meals})");
}
public string Describe() => $"{Name} the {GetType().Name}";
}
class Dog : Animal
{
public string Breed { get; }
public Dog(string name, string breed) : base(name) // run Animal's constructor first
{
Breed = breed;
}
public void Fetch() => Console.WriteLine($"{Name} the {Breed} fetches after {Meals} meal(s)");
}Rex the Dog
Rex eats (meal 1)
Rex the beagle fetches after 1 meal(s)
RexAdd a Cat : Animal with a Purr() method. Can you call a.Fetch() on the Animal a variable? Try it and read the error.
System.Object (object). That is where ToString, Equals, GetHashCode and GetType come from (Module 05).CS7036: the base class has no parameterless constructor
var d = new Dog("beagle");
class Animal
{
public string Name { get; }
public Animal(string name) => Name = name;
}
class Dog : Animal
{
public string Breed { get; }
public Dog(string breed) => Breed = breed;
}Program.cs(12,12): error CS7036: There is no argument given that corresponds to the required parameter 'name' of 'Animal.Animal(string)'Without : base(...), C# calls the base class's parameterless constructor. Animal has none: it insists on a name. So the compiler reports that nothing supplies name.
Chain to the base constructor explicitly and pass what it needs.
var d = new Dog("Rex", "beagle");
Console.WriteLine($"{d.Name} {d.Breed}");
class Animal
{
public string Name { get; }
public Animal(string name) => Name = name;
}
class Dog : Animal
{
public string Breed { get; }
public Dog(string name, string breed) : base(name) => Breed = breed;
}