Advertisement
Intermediate C# Lesson 5 of 10

Lesson 5: Inheritance in C#

Inheritance is the second pillar of OOP. It allows you to create a hierarchy of classes where a child class inherits fields and methods from a parent class. This promotes code reuse and models real-world "is-a" relationships. This lesson covers single inheritance, virtual methods, the base keyword, and best practices.

Advertisement

What Is Inheritance?

Inheritance lets a class (called derived or child) inherit members from another class (called base or parent

// Base class — shared behavior for all vehicles
public class Vehicle
{
    public string Brand { get; set; }
    public int Speed { get; set; }

    public void Accelerate()
    {
        Speed += 10;
        Console.WriteLine($"Accelerating to {Speed} km/h");
    }
}

// Derived class — inherits from Vehicle
public class Car : Vehicle
{
    public int Doors { get; set; }

    public void Honk()
    {
        Console.WriteLine("Beep! Beep!");
    }
}

// Usage
var car = new Car { Brand = "Toyota", Doors = 4 };
car.Accelerate();  // Inherited method from Vehicle
car.Honk();        // Own method

Virtual Methods and Overriding

Mark methods as virtual in the base class to allow child classes to provide their own implementation using override:

public class Animal
{
    public string Name { get; set; }

    public virtual void MakeSound()
    {
        Console.WriteLine("Some generic sound");
    }
}

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

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

// Usage
Animal dog = new Dog { Name = "Rex" };
Animal cat = new Cat { Name = "Whiskers" };

dog.MakeSound();  // Output: Woof!
cat.MakeSound();  // Output: Meow!

The Base Keyword

Use base to call the parent class's method or constructor:

public class Employee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public Employee(string name, decimal salary)
    {
        Name = name;
        Salary = salary;
    }

    public virtual void DisplayInfo()
    {
        Console.WriteLine($"{Name}: ${Salary}");
    }
}

public class Manager : Employee
{
    public int TeamSize { get; set; }

    public Manager(string name, decimal salary, int teamSize) : base(name, salary)
    {
        TeamSize = teamSize;
    }

    public override void DisplayInfo()
    {
        base.DisplayInfo();  // Call parent method
        Console.WriteLine($"Manages {TeamSize} people");
    }
}

Protected Access with Inheritance

Child classes can access protected members of the parent:

public class Person
{
    protected string SocialSecurityNumber { get; set; }  // Hidden from outside
    public string Name { get; set; }

    protected void ValidateSSN(string ssn)
    {
        // Only Person and its children can use this
    }
}

public class Employee : Person
{
    public void SetSSN(string ssn)
    {
        // Can access protected member here
        ValidateSSN(ssn);
        SocialSecurityNumber = ssn;
    }
}

Is-A vs Has-A

Inheritance (is-a) should represent true hierarchical relationships. Composition (has-a) should be used when an object contains another:

// ✓ IS-A: A dog IS-AN animal
public class Dog : Animal { }

// ✓ HAS-A: A car HAS-AN engine
public class Car
{
    public Engine Engine { get; set; }  // Composition
}

public class Engine
{
    public int Horsepower { get; set; }
}

💡 Tip: Prefer composition over inheritance. Use inheritance sparingly for true "is-a" relationships. It creates tight coupling and can make code harder to modify.

Sealed Classes (Preventing Inheritance)

Mark a class as sealed to prevent other classes from inheriting from it:

public sealed class FinalClass
{
    // No class can inherit from this
}

// ✗ Compile error
public class DerivedClass : FinalClass { }
Advertisement

🧠 Quick Check — Lesson 5

What keyword marks a method in a base class so child classes can override it?

Lesson Summary

Inheritance allows a child class to inherit fields and methods from a parent class, promoting code reuse.

Use virtual in the base class and override in the child to provide custom implementations.

The base keyword accesses parent class members from the child class.

protected members are accessible to child classes but hidden from outside.

Prefer composition (has-a) over inheritance (is-a) to reduce coupling and improve flexibility.

Use sealed to prevent further inheritance when you want to lock a class's design.

Up Next

Lesson 6: Polymorphism & Overriding

Next Lesson →