Multiple Inheritance in C#

Multiple Inheritance in C#

In this article, I will discuss multiple inheritance in C# using Interface. Please read our last article before proceeding to this article. In our last article, we discussed Interface in C#.

As we discussed earlier multiple inheritance is not supported through classes but supported through interfaces. It is not supported through classes because we will get the ambiguity problem as following.

Class 1 {Test(){}}
Class 2 {Test(){}}
Class 3 : 1, 2{}

In the above case, class 3 is inheriting from class 1 and class 2 and both these two classes contains a method with same name and same signature so while consuming the methods ambiguity arises to understand which class method has to be executed.

But, if a class is inheriting from interfaces we don’t have any ambiguity problem because the class is not consuming the members of its parent interfaces but only implementing the parent’s members.

interface 1{Test();}
interface 2{Test();}
class A : 1, 2{}

In the above case, the class is not consuming the interface members. It is only implementing the interface members so if we face any ambiguity with interface members that can be resolved in child class in two different ways.

If the method is implemented for a single time under the class both the interface will assume that the implemented method belongs to them and executes and there will not be any ambiguity.

The method can be implemented separately for each interface also under the class by providing the method name with the interface name. But in this case, while calling the method we should compulsorily use the interface reference that is created using the object of a class. We will discuss this with an example.

Example: Let us see an example to understand multiple inheritance in C#.
namespace InterfaceDemo
{
    public interface Interface1
    {
        void Test();
        void Show();
    }
    public interface Interface2
    {
        void Test();
        void Show();
    }
    class ImplementInterafce : Interface1, Interface2
    {
        public void Test()
        {
            Console.WriteLine("Test method is implemented");
        }
        public void Show()
        {
            Console.WriteLine("Show mwthod is implemented");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ImplementInterafce obj = new ImplementInterafce();
            obj.Test();
            obj.Show();
            Interface1 obj1 = new ImplementInterafce();
            obj1.Test();
            obj1.Show();
            Interface2 obj2 = new ImplementInterafce();
            obj2.Test();
            obj2.Show();
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Multiple Inheritance using Interface in C#

What is explicit interface implementation?

When each interface method is implemented separately under the child class by providing the method name along with interface name then it is called as Explicit Interface Implementation.

But in this case, while calling the method we should compulsorily use the interface reference that is created using the object of a class.

Let see an example to understand explicit interface implementation.

namespace InterfaceDemo
{
    public interface Interface1
    {
        void Test();
        void Show();
    }
    public interface Interface2
    {
        void Test();
        void Show();
    }
    class ImplementInterafce : Interface1, Interface2
    {
        //public modifier is not allowed 

        void Interface1.Test()
        {
            Console.WriteLine("Test mthod of interafce1 is implemented");
        }
        void Interface1.Show()
        {
            Console.WriteLine("Show mwthod of interafce1 is implemented");
        }
        void Interface2.Test()
        {
            Console.WriteLine("Test mthod of interface2 is implemented");
        }
        void Interface2.Show()   
        {
            Console.WriteLine("Show mwthod of interafce2 is implemented");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ImplementInterafce obj = new ImplementInterafce();
            //obj.Test();  //not possible
            //obj.Show();  //not possible

            ((Interface1)obj).Test();
            ((Interface1)obj).Show();

            Interface1 obj1 = new ImplementInterafce();
            obj1.Test();
            obj1.Show();
            Interface2 obj2 = new ImplementInterafce();
            obj2.Test();
            obj2.Show();

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Multiple Inheritance in C#

Some Important points to remember:
Point1:

We create an interface using interface keyword. Just like classes, the interface also contains properties, methods, delegates or events, but only declarations and no implementation.

Example:

interface ICustomer

{

      void Print();

}

Point2:

It is a compile-time error to provide the implementation for any interface members.

Example:

interface ICustomer

{

       void Print(){}   //Compile time error

}

Point3:

Interface members are public by default and they don’t allow explicit access modifiers.

Example:

interface ICustomer

{

          public void Print(); //Compile time error

}

Point4:

Interface cannot contain fields.

Example:

interface ICustomer

{

          int ID; //Compile time error

          void Print();

}

Point5:

when a class or a struct inherits from an interface then it’s the responsibility of the class or struct to provide the implementation for all interface members otherwise we get a compile-time error.

Example:

interface ICustomer

{

       void Print();

}

class Customer : ICustomer //Compile time error

{

}

When do you choose interface over an abstract class or vice versa?

If we want some implementation which will be the same for all the derived classes, then it is better to go for an abstract class instead of an interface. With the interface, we can move our implementation to any class that implements the interface. With the abstract class, we can share the implementation for all the derived classes in one central place, and thus avoid code duplication in the derived classes.

Can an interface inherit from another interface?

Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

Can you create an instance of an interface?

No, you cannot create an instance of an interface.

If a class inherits an interface, what are the 2 options available for that class?

Option 1: Provide Implementation for all the members inherited from the interface.

namespace Interfaces
{
    interface Interface1
    {
        void Interface1Method();
    }

    class BaseClass1 : Interface1
    {
        public void Interface1Method()
        {
            Console.WriteLine("Interface1 Method");
        }
        public void BaseClass1Method()
        {
            Console.WriteLine("BaseClass1 Method");
        }
    }
}

Option 2: If the class does not wish to provide Implementation for all the members inherited from the interface, then the class has to be marked as abstract.

namespace Interfaces
{
    interface Interface1
    {
        void Interface1Method();
    }

    abstract class BaseClass1 : Interface1
    {
        abstract public void Interface1Method();
        public void BaseClass1Method()
        {
            Console.WriteLine("BaseClass1 Method");
        }
    }
}
A class inherits from 2 interfaces and both the interfaces have the same method name as shown below. How should the class implement the drive method for both Car and Bus interface?
namespace Interfaces
{
    interface Car
    {
        void Drive();
    }
    interface Bus
    {
        void Drive();
    }

    class Demo : Car, Bus
    {
        //How to implement the Drive() Method inherited from Bus and Car
    }
}

To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method typecast the demo object to the respective interface and then call the drive method.

namespace Interfaces
{
    interface Car
    {
        void Drive();
    }
    interface Bus
    {
        void Drive();
    }

    class Demo : Car, Bus
    {
        void Car.Drive()
        {
            Console.WriteLine("Drive Car");
        }
        void Bus.Drive()
        {
            Console.WriteLine("Drive Bus");
        }

        static void Main()
        {
            Demo DemoObject = new Demo();
            ((Car)DemoObject).Drive();
            ((Bus)DemoObject).Drive();
        }
    }
}

Please refer below MSDN article for more information about the interface.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/

SUMMARY:

In this article, I try to explain Multiple Inheritance using Interface in C# step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *