C# Multilevel Inheritance

In C#, Multilevel Inheritance is a type of inheritance where a derived class is inherited from a base class, and this derived class is further inherited by another class. It creates a hierarchy of inheritance between classes. This is also known as a parent-child relationship between classes.

Multilevel Inheritance is useful when there are multiple levels of hierarchy between classes, and each derived class can inherit and add functionality to the base class.

Syntax

The syntax for creating a Multilevel Inheritance is as follows:

1class BaseClass 2{ 3 // Base class code 4} 5 6class DerivedClass : BaseClass 7{ 8 // Derived class code 9} 10 11class GrandchildClass : DerivedClass 12{ 13 // Grandchild class code 14}

Example

Let's create an example to understand the concept of Multilevel Inheritance:

1using System; 2 3class Person 4{ 5 public string FirstName { get; set; } 6 public string LastName { get; set; } 7 8 public void Display() 9 { 10 Console.WriteLine("First Name: {0}", FirstName); 11 Console.WriteLine("Last Name: {0}", LastName); 12 } 13} 14 15class Employee : Person 16{ 17 public int EmployeeID { get; set; } 18 public string Department { get; set; } 19 20 public void Show() 21 { 22 Console.WriteLine("Employee ID: {0}", EmployeeID); 23 Console.WriteLine("Department: {0}", Department); 24 } 25} 26 27class Manager : Employee 28{ 29 public int ManagerID { get; set; } 30 31 public void Print() 32 { 33 Console.WriteLine("Manager ID: {0}", ManagerID); 34 } 35} 36 37class Program 38{ 39 static void Main(string[] args) 40 { 41 Manager m = new Manager(); 42 m.FirstName = "William"; 43 m.LastName = "Max"; 44 m.EmployeeID = 1001; 45 m.Department = "IT"; 46 m.ManagerID = 9001; 47 48 m.Display(); 49 m.Show(); 50 m.Print(); 51 } 52}

In this example, we have a base class Person which contains the FirstName and LastName properties and a method Display() to display the details.

The Employee class is derived from the Person class and it contains EmployeeID and Department properties and a method Show() to display the details.

The Manager class is derived from the Employee class and it contains ManagerID property and a method Print() to display the details.

In the Main method, we create an object of the Manager class and set the values of its properties. Then we call the methods Display(), Show() and Print() to display the details.