CodeGym /Courses /C# SELF /Inheritance Syntax and base<...

Inheritance Syntax and base in C#

C# SELF
Level 20 , Lesson 1
Available

1. Introduction

In this lecture, we're gonna break down how inheritance syntax works in C#: you'll learn how to declare derived classes, what the base keyword is, and how to use it to reach up to the parent class. This not only makes your life easier when coding, but also makes your program way more elegant (and sometimes even lets you catch some extra sleep—because you won't have to fix copy-paste bugs).

Here's a simple real-life example: we've got a Vehicle class—a base, universal blueprint. All vehicles can drive, they have a color, a brand, etc.:

public class Vehicle
{
    public string Brand { get; set; }
    public string Color { get; set; }

    public void Drive()
    {
        Console.WriteLine("Let's go!");
    }
}
Base class Vehicle

Now let's say we want to add a new type of transport—a car. A car is still a vehicle, but it has its own quirks (like number of doors). It'd be weird to rewrite all the color and brand stuff again, since that's already defined!

Inheritance lets us say: "A car is a vehicle, just with a bunch of extra features."

2. How to Declare a Child Class

In C#, to create a subclass, you use a colon :. After the class name, you specify which class you're inheriting from.


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

Read it like this: the Car class inherits all the fields and methods from Vehicle and adds its own cool stuff—like number of doors.

Heads up: C# only supports single class inheritance (meaning a class can inherit from only ONE parent class). But you can implement as many interfaces as you want! (we'll talk about those later).

How does it work?

When you declare:

Car myCar = new Car();

...your myCar object gets access to all the fields/methods from Vehicle and its own properties. Example:

myCar.Brand = "Toyota";
myCar.Color = "Blue";
myCar.NumberOfDoors = 4;
myCar.Drive(); // Inherited method

Real-life scenario:
In our "growing" app, you could make a vehicle menu where the user picks a type of transport, and then the program shows all its properties. When you add a new type of vehicle, you'll write the bare minimum of new code!

3. Inheriting Constructors

When we create objects of a derived class, sometimes we want to initialize base class properties through the constructor. For example, to make sure we don't forget to set the brand and color:


public class Vehicle
{
    public string Brand { get; set; }
    public string Color { get; set; }

    public Vehicle(string brand, string color)
    {
        Brand = brand;
        Color = color;
    }
}

Now in the subclass constructor, you can (and should) call the base class constructor! For that, use the base keyword:


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

    public Car(string brand, string color, int numberOfDoors)
        : base(brand, color) // calling Vehicle constructor!
    {
        NumberOfDoors = numberOfDoors;
    }
}

What does it look like in practice?

Car bmw = new Car("BMW", "Black", 4);
Console.WriteLine($"{bmw.Brand}, {bmw.Color}, doors: {bmw.NumberOfDoors}");
bmw.Drive(); // Still works!

So bmw is both a car and a vehicle at the same time. It remembers its "parents."

4. Difference Between base and this

In C#, there are two keywords for working with class members: this and base.

  • this — refers to the current object (like its own field or method).
  • baserefers to a member of the base class (so, the parent).

When should you use base? Imagine you want to extend the logic of a method from the base class, or just initialize the base class from the derived one. For example:


public class Bicycle : Vehicle
{
    public int NumberOfGears { get; set; }

    public Bicycle(string brand, string color, int gears)
        : base(brand, color)    // calling base class constructor
    {
        NumberOfGears = gears;
    }

    public void ShowInfo()
    {
        // Using properties from the base class!
        Console.WriteLine($"{Brand} ({Color}), gears: {NumberOfGears}");
    }
}

5. The base Keyword in Methods

base isn't just for constructors! Sometimes you want to change the behavior of a base class method, but still use part of its logic.

Let's say we want the Drive method in the Car class to also print what car we're driving:


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

    public Car(string brand, string color, int numberOfDoors) 
        : base(brand, color)
    {
        NumberOfDoors = numberOfDoors;
    }

    public void DriveCar()
    {
        base.Drive(); // call base implementation
        Console.WriteLine($"Driving {Brand} with {NumberOfDoors} doors!");
    }
}

Explanation:
Calling base.Drive(); is like saying: "Dad, you tell your part of the story first, then I'll add some details!" So when you call DriveCar() you'll see:

Let's go!
Driving BMW with 4 doors!

We'll talk about overriding methods (override) in the next lectures :P

6. Inheritance Diagram

Let's visualize the relationships between classes. Here's a simple diagram (because UML is scary, especially in the morning!):

Vehicle (base)
   /         \
Car      Bicycle
  • All arrows go FROM the derived TO the base class.
  • All child classes have access to public/protected members of the base class.

Differences Between public, protected and private

A quick reminder so you don't get confused.
In a derived class, you can see:

Modifier Visible in child?
public Yes
protected Yes
private No

Common mistake:
Trying to access a private field from a child class:


public class Vehicle
{
    private string secret = "Nobody will ever know!";
}

public class Car : Vehicle
{
    public void RevealSecret()
    {
        Console.WriteLine(secret); // Error! Not visible.
    }
}
private — for the base class only, no family secrets!

Comparison: Base vs. Derived Class

Vehicle Car (child)
Brand has inherits
Color has inherits
Drive() has inherits (or extends)
NumberOfDoors no own (unique property)

7. Example

If we're still building our simple "Transport Tracker" app, we could set it up like this:


public class Vehicle
{
    public string Brand { get; set; }
    public string Color { get; set; }

    public Vehicle(string brand, string color)
    {
        Brand = brand;
        Color = color;
    }

    public void Drive()
    {
        Console.WriteLine($"{Brand} {Color} drove off!");
    }
}

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

    public Car(string brand, string color, int numberOfDoors)
        : base(brand, color)
    {
        NumberOfDoors = numberOfDoors;
    }

    public void ShowCar()
    {
        Console.WriteLine($"Brand: {Brand}, Color: {Color}, Doors: {NumberOfDoors}");
    }
}

public class Bicycle : Vehicle
{
    public int NumberOfGears { get; set; }

    public Bicycle(string brand, string color, int numberOfGears)
        : base(brand, color)
    {
        NumberOfGears = numberOfGears;
    }
}

In the main method, you can create a list of vehicles and describe them in different ways:

Car ford = new Car("Ford", "Red", 4);
ford.ShowCar();
ford.Drive();

Bicycle trek = new Bicycle("Trek", "Green", 21);
trek.Drive();

8. Mistakes, Gotchas, and a Bit of Humor

Super common mistake — forgetting to call the base constructor in the child class. If Vehicle doesn't have a parameterless constructor and you don't call base(...), you'll get a compile error: the compiler will complain it can't initialize the base. It's like trying to build a second floor without the first. Doesn't work. You'll have to send the data upstairs.

Second mistake: forgetting that fields/methods in the base class marked private are NOT visible in children. If you want to leave something for the "kids," use protected (more on that in the next lectures).

And most importantly: inheritance is super handy, but don't build crazy-deep hierarchies. In real life, if your inheritance chain is more than two or three levels deep, something probably went wrong. It's way too easy to get lost in who inherits from whom, and why you even needed all that in the first place.

2
Task
C# SELF, level 20, lesson 1
Locked
Inheritance using the base class constructor
Inheritance using the base class constructor
2
Task
C# SELF, level 20, lesson 1
Locked
Using the base keyword to call a base class method
Using the base keyword to call a base class method
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION