Inheritance in C#
What is Inheritance?
Inheritance is one of the fundamental concepts of object-oriented programming (OOP) in C#. It allows a class (derived class) to inherit fields and methods from another class (base class). Inheritance promotes code reuse and establishes a relationship between classes.
Why Use Inheritance?
Inheritance allows you to create new classes that reuse, extend, and modify the behavior of existing classes. It provides a clear structure and reduces code duplication.
Example: Inheritance in C#
Here’s an example where a Vehicle
class is the base class, and Car
is the derived class inheriting from Vehicle
.
Example Code:
public class Vehicle
{
public string Make { get; set; }
public int Year { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Make: {Make}, Year: {Year}");
}
}
public class Car : Vehicle
{
public int NumberOfDoors { get; set; }
public void DisplayCarInfo()
{
Console.WriteLine($"Make: {Make}, Year: {Year}, Doors: {NumberOfDoors}");
}
}
// Usage
Car car = new Car();
car.Make = "Toyota";
car.Year = 2022;
car.NumberOfDoors = 4;
car.DisplayCarInfo(); // Output: Make: Toyota, Year: 2022, Doors: 4
In this example, the Car
class inherits the properties and methods from the Vehicle
class and adds additional functionality with the NumberOfDoors
property and DisplayCarInfo
method.
Types of Inheritance
- Single Inheritance: A derived class inherits from a single base class.
- Multilevel Inheritance: A class is derived from a class that is also derived from another class.
- Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
The base
Keyword
The base
keyword is used to access members of the base class from within a derived class. It can be used to call base class constructors, methods, or properties.
Example of Using base
Keyword:
public class Vehicle
{
public string Make { get; set; }
public Vehicle(string make)
{
Make = make;
}
public void DisplayInfo()
{
Console.WriteLine($"Vehicle Make: {Make}");
}
}
public class Car : Vehicle
{
public Car(string make) : base(make) // Using 'base' to call the base class constructor
{
}
}
// Usage
Car car = new Car("Honda");
car.DisplayInfo(); // Output: Vehicle Make: Honda
In this example, the base
keyword is used to call the base class constructor from the derived class constructor.
Key Points to Remember
- Inheritance enables code reuse by allowing derived classes to inherit fields and methods from base classes.
- The
base
keyword is used to access members of the base class. - Inheritance promotes hierarchical relationships between classes, creating a clear class structure.
- In C#, multiple inheritance is not supported directly, but interfaces can be used to achieve similar results.