C# Inheritance Lesson

What is Inheritance in C#?

Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows a class (called the child or derived class) to inherit properties and methods from another class (called the parent or base class).

This means the child class gets all the features of the parent class, plus it can have its own unique features. Itโ€™s like inheriting traits from your parents but adding your own style.

Why Use Inheritance?

Basic Example

class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating food");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

class Program
{
    static void Main()
    {
        Dog dog = new Dog();
        dog.Eat();  // inherited from Animal
        dog.Bark(); // own method
    }
}

Here, Dog inherits from Animal. That means Dog has access to Eat() from Animal, and also its own method Bark().

Key Points

Quiz: Test Your Knowledge

1. What symbol is used to indicate inheritance in C#?

2. Which class is the parent class in inheritance?

3. Which members are inherited by child classes?

4. If class Cat inherits from Animal, which method call is valid?

5. What happens if you create an object of the child class?