C# Inheritance
Inheriting fields and methods from other classes.
C# Inheritance (Subclass and Superclass)
In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories:
- Derived Class (child) - the class that inherits from another class
- Base Class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the fields and methods from the Vehicle class (parent):
Examples
Inheritance Example
Car inherits brand and honk from Vehicle.
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)
{
Car myCar = new Car();
myCar.honk();
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}