Inheritance basics
Learn to inherit from a base class with the : operator.
Inheritance basics
Inheritance is when a class reuses another class's members. In C# it is written with a colon (:): class Dog : Animal { ... }.
Here Animal is the base class, Dog is the derived class. Dog automatically gains the public and protected members of Animal. This reduces code duplication: you write shared behavior once and reuse it across subtypes.
Base and derived class
The base class holds shared properties and methods; the derived class adds its own specific members. For example, if Animal has Name and Eat, Dog adds Bark.
C# supports single inheritance: a class can inherit from only one base class. If you need two, use interfaces. The derived class cannot call the base constructor directly; it chains with the base keyword.
Exercise Define Animal and Dog classes
Define an Animal base class with a public string Name { get; set; } property. Then declare a derived class Dog : Animal with a public void Bark() method (body: Console.WriteLine("Woof");). Inside Main create a new Dog(), set Name = "Rex", print Name and call Bark().
Show example solution
Animal and add Bark. In Main write Dog d = new Dog(); d.Name = "Rex"; Console.WriteLine(d.Name); d.Bark();
Example solution:
using System;
class Animal
{
public string Name { get; set; }
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof");
}
}
class Program
{
static void Main()
{
Dog d = new Dog();
d.Name = "Rex";
Console.WriteLine(d.Name);
d.Bark();
}
}
Test yourself
-
Which is an inheritance declaration?
- class Dog : Animal { }
- class Dog extends Animal { }
- class Dog -> Animal { }
- class Dog ( Animal ) { }
Show answer
class Dog : Animal { } — Correct. In C# inheritance is written with a colon.
-
Complete the inheritance declaration
class Dog ____ Animal { }Show answer
class Dog : Animal { } -
Match each term to its role
- Animal
- Base class
- Dog
- Derived class
- :
- Inheritance operator
- Bark
- Method specific to Dog