What are the different types of Inheritance?

 


In C#, you can implement inheritance using the : (colon) symbol to denote the inheritance relationship between classes. Here are the different types of inheritance that you can use in C#:

Single Inheritance: C# supports single inheritance, where a class can inherit from only one base class.
public class Parent { public void Method1() { Console.WriteLine("Method from Parent class"); } } public class Child : Parent { public void Method2() { Console.WriteLine("Method from Child class"); } }

 

Multiple Inheritance (through Interfaces): C# does not support multiple inheritance for classes, but it does support multiple inheritance through interfaces. Interfaces allow a class to inherit multiple method signatures without the actual implementation.

public interface IInterface1 { void Method1(); } public interface IInterface2 { void Method2(); } public class Child : IInterface1, IInterface2 { public void Method1() { Console.WriteLine("Method from IInterface1"); } public void Method2() { Console.WriteLine("Method from IInterface2"); } }

 

Multilevel Inheritance: C# supports multilevel inheritance, where a class can inherit from a base class, which, in turn, inherits from another base class.

public class Grandparent { public void Method1() { Console.WriteLine("Method from Grandparent class"); } } public class Parent : Grandparent { public void Method2() { Console.WriteLine("Method from Parent class"); } } public class Child : Parent { public void Method3() { Console.WriteLine("Method from Child class"); } }

 

Hierarchical Inheritance: C# also supports hierarchical inheritance, where multiple classes inherit from the same base class.

public class Parent { public void Method1() { Console.WriteLine("Method from Parent class"); } } public class Child1 : Parent { public void Method2() { Console.WriteLine("Method from Child1 class"); } } public class Child2 : Parent { public void Method3() { Console.WriteLine("Method from Child2 class"); } }

 

Hybrid Inheritance (using Interfaces): You can use interfaces to simulate hybrid inheritance in C#.

public interface IInterface1 { void Method1(); } public interface IInterface2 { void Method2(); } public class Parent : IInterface1 { public void Method1() { Console.WriteLine("Method from IInterface1"); } } public class Child : Parent, IInterface2 { public void Method2() { Console.WriteLine("Method from IInterface2"); } }

Remember that in C#, a class can only directly inherit from a single base class. However, through interfaces, you can achieve some form of multiple inheritance by inheriting from multiple interfaces.

Post a Comment

Previous Post Next Post