C# Multiple Inheritance with Interface - Programming Example

In this chapter you will learn
  • Applying multiple inheritance using Interface
  • Programming Example

C# doesn't allow multiple inheritance with classes but it can be implemented using interface. The reason behind is:

  1. Multiple inheritance add too much complexity with little benefit.
  2. There are huge chances of conflicting base class member. For example, if there is a method calculate() in two base class and both are doing different calculation. What happened if user call calculate() in child class? Which method will work?
  3. Inheritance with Interface provides same job of multiple inheritance.
  4. Multiple Inheritance inject a lots of burden into implementation and it cause slow program execution.
 

Inheritance with Interface

As you learned that c# doesn't provide multiple inheritance with classes, even you can implement it using Interface. Just see the programming example.

Programming Examples and Codes

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

namespace Interface_Inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            child ch = new child();
            ch.message();
            Console.ReadKey();
        }
    }    
    public interface Ibase1
    {
        void message();  
    }
    public interface Ibase2
    {
        void message();
    }
    public class child : Ibase1, Ibase2
    {
        public void message()
        {
            Console.WriteLine("Hello Multiple Inheritance");
        }
    }
}

Output
Hello Multiple Inheritance
_

Summary

In this chapter you learned multiple inheritance with Interface. Because the method defined inside interface has no body implementation so it must be define in child class. Interface helps to remove member confliction in child class. In the next chapter you will learn about Sealed Inheritance in C#.

More Articles