Multiple Class Inheritance Using Interfaces in C#

Multiple Class Inheritance Using Interfaces in C#
Multiple Class Inheritance Using Interfaces in C#

As you know, multiple class inheritance is not possible in C#.  But you can achieve this goal using interfaces because multiple interface inheritance is allowed in C#.  We can learn this thing better with an example.

Create 2 interfaces IA and IB.  IA contains a method PrintA() and IB contains a method PrintB().  Create 3 classes A, B, and C.  Class A and B inheriting from interfaces IA and IB respectively.  Class C is inheriting from interfaces IA and IB.  As per condition, class A and B must provide implementation for their respective interface members.  Same goes for class C, but with a little twist.  In class C, we will create instances of class A and class B.  Then, we will create 2 methods PrintA() and PrintB().  Because we have instantiated class A and B, we have access to their methods.  We will call those methods using PrintA() and PrintB() methods available in class C.

This is a bit of work, which will give you access to methods available in both the classes A and B by creating an instance of class C.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{
    //interface A
    interface IA
    {
        void PrintA();
    }

    //interface B
    interface IB
    {
        void PrintB();
    }

    
    class A:IA    
    {
        public void PrintA()
        {
            Console.WriteLine("Class A");
        }
    }

    class B:IB
    {
        public void PrintB()
        {
            Console.WriteLine("Class B");
        }
    }

    class C:IA,IB
    {
        A _a = new A();
        B _b = new B();

        public void PrintA()
        {
            _a.PrintA();
        }

        public void PrintB()
        {
            _b.PrintB();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            C _c = new C();
            _c.PrintA();
            _c.PrintB();     
        }
            
    }
}

Output:

Class A
Class B
Press any key to continue . . .