Inheritance in C#

Inheritance lets one class build on another, so shared code lives in one place. You will spot repeated code, generalize it into a base class, and specialize it in derived classes with constructors and overridden methods.

Updated

DRY Code in C#

  1. DRY Code in C# (Novice): When several classes repeat the same properties and methods, the code breaks the DRY rule (Don't Repeat Yourself). One class that does everything isn't the answer either.

Introduction to Inheritance in C#

  1. Introduction to Inheritance in C#: an overview (Apprentice): Inheritance lets one class build on another. An archer is a character, so Archer inherits everything Character has, and adds what only archers have.
  2. Generalization vs Specialization (Apprentice): Generalization moves what similar classes share into a base class; specialization keeps what makes each one different in its derived class.
  3. Inheritance in C# (Apprentice): A derived class names its base class after a colon. It inherits every member of the base class, but its code can use only the public and protected ones, never the private ones; and every class inherits from object in the end.
  4. Inheritance and Constructors (Journeyman): When a base class has a constructor with parameters, every derived class must call it with base(...). The base class's constructor always runs first.
  5. Overriding Methods (Journeyman): A base class marks a method virtual so derived classes may change it; a derived class replaces it with override, and can still run the base version with base.MethodName().

Exercise: Inheritance

  1. Exercise: Inheritance (Apprentice): Finish a café menu's Drink and Pastry classes so they inherit from MenuItem, with constructors that call base(...), an overridden Price and an overridden ToString().