CodeGym /Courses /C# SELF /The Concept of Inheritance

The Concept of Inheritance

C# SELF
Level 20 , Lesson 0
Available

1. Introduction

Inheritance in programming is a lot like inheritance in real life. For example, you might inherit your eye color, nose shape, or even a talent for drawing from your parents. You get these traits "by default", and you don't have to create them from scratch. But you can also develop your own unique features that your parents don't have.

In programming, it works pretty much the same way:

  • One class (we'll call it the base class or parent class, sometimes superclass) defines common characteristics (properties) and behavior (methods) that all its "descendants" have.
  • Another class (called the derived class or child class, sometimes subclass) inherits all these common traits from its parent. It automatically gets all the public and protected properties and methods of the base class. No need to declare them again.
  • At the same time, the derived class can add its own unique properties and methods that the parent class doesn't have.
  • Sometimes, the derived class can even change the behavior of inherited methods (but we'll talk about that in later lectures, that's called polymorphism).

The key concept of inheritance is summed up by the phrase "is-a" (is-a relationship). Imagine you're writing your own game with mages, warriors, and archers:

  • Warrior is a Character.
  • Mage is a Character.
  • Archer is a Character.

If Warrior is a Character, then it should have everything any Character has, plus something unique to Warrior.

2. Inheritance Syntax

Let's check out an example and do a bit of coding.

Syntax Basics


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

    public void Move()
    {
        Console.WriteLine($"{Name} moves.");
    }
}

// Child class
public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine($"{Name} barks: Woof!");
    }
}

Check out the colon after the class name Dog. Here we're saying: Dog inherits everything from Animal.

Everything public and protected in Animal shows up in Dog!

Using Inheritance

Let's try using these classes in our console app:


var dog = new Dog();
dog.Name = "Sharik"; // property Name inherited from Animal
dog.Move();         // method Move inherited from Animal
dog.Bark();         // Dog's own method

// Output:
// Sharik moves.
// Sharik barks: Woof!

You can also create a cat to spice up your "zoo":

public class Cat : Animal
{
    public void Meow()
    {
        Console.WriteLine($"{Name} meows: Meow!");
    }
}

var cat = new Cat();
cat.Name = "Murka";
cat.Move();
cat.Meow();

3. How Inheritance Saves You Work

When you have a bunch of similar entities, you don't have to copy code over and over. Inheritance is like a master copy: you define the logic once, and all descendants get it.

Visualization: Inheritance Tree


.   Animal
     /    \
  Dog    Cat
Class inheritance diagram
Class Property Name Method Move Own method
Animal + + -
Dog + + Bark()
Cat + + Meow()

Another Example — Expanding an App

Let's say we want to make a system to keep track of different types of people. Remember the old approach:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// Now let's add an employee
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
}

Not very convenient! The name data is duplicated. With inheritance, you do it right:


public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person
{
    public string Position { get; set; }
}

public class Student : Person
{
    public int Grade { get; set; }
}
Inheritance to eliminate code duplication

Now both Employee and Student already have FirstName and LastName — no need to write them again. You can imagine how easy it is to expand your system for different roles now.

That's the magic of inheritance: we described the common traits in the base class once, and then just "extended" its functionality in derived classes by adding specific details.

4. Benefits of Inheritance

Code Reusability: This is the most obvious benefit. You don't have to write the same code in multiple places. Write it once — use it many times. Your code gets drier and cleaner (in programming we say "Don't Repeat Yourself" — DRY).

Easier Maintenance: If you need to change the movement logic, you change it in just one place — in the base class Animal. All derived classes automatically get this change. Imagine how much time that saves in a big project!

Creating Hierarchies: Inheritance lets you model "is-a" relationships from the real world, making logical and understandable structures. Warrior is a Character, Mage is a Character. This makes your code more structured and easier to get.

Foundation for Polymorphism: Even though we haven't dug into polymorphism yet, inheritance is its cornerstone. Polymorphism lets you work with objects of different derived classes using the common interface of the base class. For example, you can have a list of all Animals (whether they're Dog, Cat, or other animals) and call the Move method on them without caring what specific type each animal is. That's a super powerful thing, and we'll definitely come back to it!

5. Inheritance Nuances and Features

Single Inheritance in C#: Unlike some other languages (like C++), C# only supports single inheritance. That means a class can only inherit from one base class. You can't inherit from both Animal and, say, Vehicle (if such a class existed).

All classes implicitly inherit from object: Fun fact! If you don't specify a base class, your class automatically inherits from System.Object. That's the most basic class in .NET, and it gives you some fundamental methods like ToString(), Equals(), GetHashCode(). So when you override ToString() in your classes, you're actually overriding a method inherited from object!

Constructors aren't inherited: The derived class doesn't inherit the base class's constructors. You have to explicitly define constructors in the derived class. But if the base class has a constructor with parameters, you MUST call one of the base class's constructors from the derived class's constructor. You do this with the base keyword.

Private members aren't accessible: private members of the base class aren't directly accessible from the derived class. They exist in the object, but you can't access them by name from the derived class code. If you want members to be available to derived classes but not to the whole world, use the protected access modifier.

6. Hierarchy Visualization

To better understand inheritance relationships, diagrams are often used. One of the most common is the class diagram from UML (Unified Modeling Language). For a simple animal example, it would look like this:

classDiagram
    class Animal {
        + string Name
        + Move()
    }

    class Dog {
        + Bark()
    }

    class Cat {
        + Meow()
    }

    Animal <|-- Dog : inherits
    Animal <|-- Cat : inherits
UML class diagram for the inheritance example

On this diagram, the arrow with an unfilled triangle (from Dog to Animal, from Cat to Animal) means an inheritance relationship: "is-a" (is-a relationship).

7. Practical Use of Inheritance

Inheritance isn't just an academic concept, it's one of the pillars of modern programming that's used all over real projects:

GUI Development: In WPF, WinForms, MAUI (frameworks for building desktop apps on .NET), almost all controls (buttons, text boxes, windows) inherit from a common base class like Control or UIElement. This lets them have common properties like size, position, visibility, and common methods like event handling.
For example, Button is a Control, and TextBox is a Control.

Game Engines: Inheritance is perfect for building hierarchies of game objects: GameObjectCharacterPlayer/Enemy or VehicleCar/Motorcycle.

Working with Databases (ORM): In frameworks like Entity Framework Core, you often define a base class for all your entities, like BaseEntity, which might have properties like Id (record ID in the database) or CreatedAt (record creation date). All your specific entities (like User, Product, Order) will inherit from BaseEntity, automatically getting these properties.

Testing: Inheritance is used in test frameworks (like xUnit, NUnit), where you can create base test classes with common setup and teardown logic, and your specific test classes inherit from them.

Libraries and Frameworks: The .NET standard library itself uses inheritance a lot. For example, many collections and types inherit from common base classes or implement common interfaces (which we'll talk about later).

In C# and .NET interviews, questions about inheritance, its principles (DRY, "is-a"), and how it differs from other concepts (like composition or interfaces) are basic and super common. Being able not just to explain what it is, but to give real-life or code examples — that's a really valuable skill.

So, you see, inheritance isn't just a "language feature," it's a powerful tool for structuring code, reducing duplication, and building logically connected systems. It's the key to writing scalable and maintainable code.

2
Task
C# SELF, level 20, lesson 0
Locked
Inheritance and Base Class
Inheritance and Base Class
2
Task
C# SELF, level 20, lesson 0
Locked
Extending Functionality
Extending Functionality
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION