C# Inheritance

What is Inheritance?

Inheritance allows one class to inherit fields and methods from another class.

This helps reduce code duplication and creates a relationship between classes.

Loading...
Output:

Creating a Child Class

In C#, a child class inherits from a parent class using the : symbol.

The child class automatically gets access to all public members of the parent class.

Loading...
Output:

Using Inherited Methods

Once a class inherits from another, it can use its methods without redefining them.

This allows you to reuse existing functionality.

Loading...
Output:

Adding New Behavior

A child class can also define its own methods in addition to inherited ones.

This allows the child class to extend the functionality of the parent.

Loading...
Output:

Method Overriding

A child class can override a method from the parent class to provide its own behavior.

The parent method must be marked virtual, and the child uses override.

Loading...
Output:

The base Keyword

The base keyword refers to the parent class.

It can be used to call parent methods or constructors.

Loading...
Output:

Constructors in Inheritance

When a child object is created, the parent constructor runs first.

You can use base() to pass values to the parent constructor.

Loading...
Output:

Why Use Inheritance?

Inheritance helps organize code and promotes reuse.

  • Reduces duplication
  • Creates logical relationships
  • Improves scalability

Practice

Create a Vehicle class with a Start() method. Then create a Car class that inherits from Vehicle and uses the method.

Loading...
Output:

Need Help?