C# Hybrid Inheritance
In object-oriented programming, inheritance is a mechanism that allows one class to inherit properties and behavior from another class. Hybrid inheritance, also known as a combination of different types of inheritance, is a combination of two or more types of inheritance. In C#, hybrid inheritance is achieved through a combination of multiple and multilevel inheritance.
Multiple Inheritance
Multiple inheritance allows a class to inherit properties and behavior from more than one base class. In C#, multiple inheritance is not allowed, which means that a class cannot inherit from more than one class at the same level.
Multilevel Inheritance
Multilevel inheritance allows a class to inherit properties and behavior from its parent class, which in turn inherits properties and behavior from its parent class. This creates a chain of inheritance, where each class inherits properties and behavior from its parent class.
Hybrid Inheritance Example
Here is an example of how hybrid inheritance can be implemented in C#:
1using System; 2 3public class Person 4{ 5 public string Name { get; set; } 6 7 public void Introduce() 8 { 9 Console.WriteLine("Hi, my name is " + Name); 10 } 11} 12 13public class Employee : Person 14{ 15 public int EmployeeId { get; set; } 16} 17 18public interface IManager 19{ 20 void AssignTask(); 21} 22 23public class Manager : Employee, IManager 24{ 25 public void AssignTask() 26 { 27 Console.WriteLine("Task assigned"); 28 } 29} 30 31public class Program 32{ 33 public static void Main() 34 { 35 Manager manager = new Manager(); 36 manager.Name = "William"; 37 manager.EmployeeId = 123; 38 manager.Introduce(); 39 manager.AssignTask(); 40 } 41}
In this example, we have a Person
class that has a Name
property and an Introduce()
method. The Employee
class inherits from the Person
class and adds an EmployeeId
property. The Manager
class inherits from the Employee
class and also implements the IManager
interface, which has an AssignTask()
method.
In the Main()
method, we create an instance of the Manager
class, set the Name
and EmployeeId
properties, and then call the Introduce()
and AssignTask()
methods.
The output of the program is:
1Hi, my name is William 2Task assigned
This example demonstrates how hybrid inheritance can be used to create a class hierarchy that combines different types of inheritance to achieve the desired functionality.