C# Inheritance Basics

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class to inherit properties and methods from an existing class. This promotes code reusability and establishes a clear hierarchical relationship between classes, often referred to as a "is-a" relationship.

What is Inheritance?

In C#, the class that is inherited from is called the base class (or parent class), and the class that inherits is called the derived class (or child class). The derived class automatically gains access to the non-private members (fields, properties, methods) of its base class.

Syntax for Inheritance

To indicate that a class derives from another, you use a colon (:) followed by the name of the base class after the derived class name.


public class Vehicle
{
    public string Make { get; set; }
    public string Model { get; set; }

    public virtual void StartEngine()
    {
        Console.WriteLine("Engine started.");
    }
}

public class Car : Vehicle
{
    public int NumberOfDoors { get; set; }

    // Override the base class method
    public override void StartEngine()
    {
        Console.WriteLine("Car engine started smoothly.");
    }
}
            

Key Concepts

Example Usage

Let's see how we can use the Car class that inherits from Vehicle:


using System;

public class Program
{
    public static void Main(string[] args)
    {
        // Create an instance of the derived class
        Car myCar = new Car();
        myCar.Make = "Toyota";
        myCar.Model = "Camry";
        myCar.NumberOfDoors = 4;

        Console.WriteLine($"Car: {myCar.Make} {myCar.Model}");
        Console.WriteLine($"Doors: {myCar.NumberOfDoors}");

        // Call the inherited method (overridden version)
        myCar.StartEngine();

        // We can also use a base class reference to a derived class object
        Vehicle genericVehicle = myCar;
        genericVehicle.StartEngine(); // Still calls the overridden Car.StartEngine()
    }
}
            

Benefits of Inheritance

Inheritance is a cornerstone of object-oriented design. Understanding how to effectively use it will significantly improve your C# programming skills.