C# Inheritance

C# Inheritance (Derived and Base Class)

In C#, it is possible to inherit fields and methods from one class to another. This is one of the most powerful features of Object-Oriented Programming because it promotes heavy code reusability.

We group inheritance into two categories:


The : Symbol

To inherit from a class, use the colon symbol :.

Let's look at an example. We have a base class called Vehicle, and a child class called Car. The Car class will inherit all the public fields and methods from Vehicle.

Example: Inheritance

using System;

class Vehicle // Base class (parent) { public string brand = "Ford"; // Vehicle field public void Honk() // Vehicle method { Console.WriteLine("Tuut, tuut!"); } }

class Car : Vehicle // Derived class (child) { public string modelName = "Mustang"; // Car field }

class Program { static void Main(string[] args) { // Create a myCar object Car myCar = new Car(); // Call the Honk() method (inherited from the Vehicle class!) myCar.Honk(); // Display the value of brand (from Vehicle) and modelName (from Car) Console.WriteLine(myCar.brand + " " + myCar.modelName); } }

Notice how the Car object has full access to Honk() and brand, even though they were never explicitly written inside the Car class!


The sealed Keyword

Sometimes, you want to prevent a class from being inherited. If you don't want other classes to inherit from a class, use the sealed keyword.

Example: Sealed Class

using System;

sealed class Vehicle { public string brand = "Ford"; }

// If you try to inherit a sealed class, C# will throw an error! /* class Car : Vehicle { public string modelName = "Mustang"; } */

class Program { static void Main(string[] args) { Vehicle myObj = new Vehicle(); Console.WriteLine(myObj.brand); } }

Why And When To Use "Inheritance"?


Exercise

?

Which symbol is used to inherit from a class in C#?