LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2418 min read

Inheritance

Learn how classes can inherit fields and methods from a base class using C# inheritance.

What is Inheritance?

Inheritance lets a class (the derived class) reuse fields and methods from another class (the base class), modeling an "is-a" relationship — a Dog is an Animal, a Car is a Vehicle.

Base and Derived Classes

class Animal
{
public string Name;
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
class Dog : Animal // Dog inherits from Animal
{
public void Bark()
{
Console.WriteLine($"{Name} says woof!");
}
}
var dog = new Dog { Name = "Rex" };
dog.Eat(); // inherited from Animal
dog.Bark(); // defined in Dog
Output

Click Run to see what this code prints.

The base Keyword

`base` lets a derived class call its parent class's constructor or methods explicitly.

class Animal
{
public string Name;
public Animal(string name) { Name = name; }
}
class Dog : Animal
{
public Dog(string name) : base(name) // calls Animal's constructor
{
}
}

Single Inheritance

C# only allows a class to inherit from one base class directly (unlike some languages that allow multiple inheritance). To share behavior across unrelated classes, C# uses interfaces instead — covered later in this course.

FAQs

No — only `protected` or `public` members are accessible; `private` members stay fully hidden even from derived classes.

Summary

  • Inheritance lets a derived class reuse a base class's members.
  • `base` calls the parent's constructor or methods explicitly.
  • C# supports single inheritance; interfaces fill the gap for shared behavior across unrelated classes.
Next Lesson →

Polymorphism