Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Type.GetInterfaces() Method
Next article icon

C# | Multiple inheritance using interfaces

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Introduction:

  1. Multiple inheritance refers to the ability of a class to inherit from multiple base classes. C# does not support multiple inheritance of classes, but it does support
  2. multiple inheritance using interfaces. An interface is a collection of abstract methods that a class can implement to provide specific behavior. A class can
  3. implement multiple interfaces, which allows it to inherit functionality from multiple sources.

Advantages:

  1. Flexibility: Multiple inheritance using interfaces provides a flexible way to add functionality to a class without inheriting implementation details from a base class.
  2. Code reuse: By implementing multiple interfaces, a class can reuse code from multiple sources, making it easier to write efficient and maintainable code.
  3. Separation of concerns: Multiple inheritance using interfaces promotes the separation of concerns, making it easier to understand and maintain the code.

Disadvantages:

  1. Complexity: Implementing multiple interfaces can make the code more complex and harder to understand, especially if there are a large number of interfaces or if they have complex relationships with each other.
  2. Naming conflicts: Multiple inheritance using interfaces can lead to naming conflicts if two or more interfaces define methods or properties with the same name and signature.
  3. Inconsistent behavior: If two or more interfaces define methods with the same name and signature but different behaviors, it can lead to inconsistent behavior in the class that implements them.

 

Sure, here’s an example code demonstrating multiple inheritance using interfaces in C#:

C#




using System;
 
interface IShape
{
    double GetArea();
}
 
interface IColor
{
    string GetColor();
}
 
class Rectangle : IShape, IColor
{
    private double length;
    private double breadth;
    private string color;
 
    public Rectangle(double length, double breadth, string color)
    {
        this.length = length;
        this.breadth = breadth;
        this.color = color;
    }
 
    public double GetArea()
    {
        return length * breadth;
    }
 
    public string GetColor()
    {
        return color;
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        Rectangle rect = new Rectangle(5, 10, "blue");
        Console.WriteLine("Area of rectangle: " + rect.GetArea());
        Console.WriteLine("Color of rectangle: " + rect.GetColor());
    }
}
 
 
Output
Area of rectangle: 50 Color of rectangle: blue

In this example, we have two interfaces: IShape and IColor. The Rectangle class implements both of these interfaces and provides its own implementation for the methods defined in the interfaces. The Program class creates an instance of the Rectangle class and calls its GetArea() and GetColor() methods.

The advantages of using multiple inheritance through interfaces include:

  1. Allows a class to inherit from multiple sources, providing more flexibility in creating class hierarchies.
  2. Interfaces enforce a contract that implementing classes must adhere to, promoting consistency and predictability in the codebase.
  3. Interfaces allow for a separation of concerns, allowing for more modular and reusable code.

The disadvantages of multiple inheritance through interfaces include:

  1. The need for more boilerplate code, as interfaces require implementing classes to provide their own implementation for each method.
  2. Multiple inheritance can make the class hierarchy more complex and harder to understand.
  3. Interfaces cannot contain any implementation, only method signatures, which may be limiting in some cases.

Some recommended reference books for learning more about multiple inheritance using interfaces in C# include:

  1. C# 9.0 in a Nutshell: The Definitive Reference by Joseph Albahari and Ben Albahari
  2. Pro C# 9 with .NET 5: With Visual Studio 2019 by Andrew Troelsen and Philip Japikse
  3. C# 9 and .NET 5 – Modern Cross-Platform Development: Build intelligent apps, websites, and services with Blazor, ASP.NET Core, and Entity Framework Core
  4. using Visual Studio Code by Mark J. Price.

Reference books:

  1. “C# 9 and .NET 5 – Modern Cross-Platform Development: Build intelligent apps, websites, and services with Blazor, ASP.NET Core, and Entity Framework Core using Visual Studio Code, 5th Edition” by Mark J. Price
  2. “C# in a Nutshell: The Definitive Reference” by Joseph Albahari and Ben Albahari
  3. “Pro C# 9 with .NET 5: Comprehensively revised for Visual Studio 2019” by Andrew Troelsen and Philip Japikse.

In Multiple inheritance, one class can have more than one superclass and inherit features from all its parent classes. As shown in the below diagram, class C inherits the features of class A and B. But C# does not support multiple class inheritance. To overcome this problem we use interfaces to achieve multiple class inheritance. With the help of the interface, class C( as shown in the above diagram) can get the features of class A and B. Example 1: First of all, we try to inherit the features of Geeks1 and Geeks2 class into GeeksforGeeks class, then the compiler will give an error because C# directly does not support multiple class inheritance. 

CSharp




// C# program to illustrate
// multiple class inheritance
using System;
using System.Collections;
 
// Parent class 1
class Geeks1 {
 
    // Providing the implementation
    // of languages() method
    public void languages()
    {
 
        // Creating ArrayList
        ArrayList My_list = new ArrayList();
 
        // Adding elements in the
        // My_list ArrayList
        My_list.Add("C");
        My_list.Add("C++");
        My_list.Add("C#");
        My_list.Add("Java");
 
        Console.WriteLine("Languages provided by GeeksforGeeks:");
        foreach(var elements in My_list)
        {
            Console.WriteLine(elements);
        }
    }
}
 
// Parent class 2
class Geeks2 {
 
    // Providing the implementation
    // of courses() method
    public void courses()
    {
 
        // Creating ArrayList
        ArrayList My_list = new ArrayList();
 
        // Adding elements in the
        // My_list ArrayList
        My_list.Add("System Design");
        My_list.Add("Fork Python");
        My_list.Add("Geeks Classes DSA");
        My_list.Add("Fork Java");
 
        Console.WriteLine("\nCourses provided by GeeksforGeeks:");
        foreach(var elements in My_list)
        {
            Console.WriteLine(elements);
        }
    }
}
 
// Child class
class GeeksforGeeks : Geeks1, Geeks2 {
}
 
public class GFG {
 
    // Main method
    static public void Main()
    {
 
        // Creating object of GeeksforGeeks class
        GeeksforGeeks obj = new GeeksforGeeks();
        obj.languages();
        obj.courses();
    }
}
 
 

Runtime Error:

prog.cs(61, 30): error CS1721: `GeeksforGeeks’: Classes cannot have multiple base classes (`Geeks1′ and `Geeks2′) prog.cs(35, 7): (Location of the symbol related to previous error)

But we can indirectly inherit the features of Geeks1 and Geek2 class into GeeksforGeeks class using interfaces. As shown in the below diagram. Example 2: Both GFG1 and GFG2 interfaces are implemented by Geeks1 and Geeks2 class. Now Geeks1 and Geeks2 class define languages() and courses() method. When a GeeksforGeeks class inherits GFG1 and GFG2 interfaces you need not to redefine languages() and courses() method just simply create the objects of Geeks1 and Geeks2 class and access the languages() and courses() method using these objects in GeeksforGeeks class. 

CSharp




// C# program to illustrate how to
// implement multiple class inheritance
// using interfaces
using System;
using System.Collections;
 
// Interface 1
interface GFG1 {
    void languages();
}
 
// Parent class 1
class Geeks1 : GFG1 {
 
    // Providing the implementation
    // of languages() method
    public void languages()
    {
 
        // Creating ArrayList
        ArrayList My_list = new ArrayList();
 
        // Adding elements in the
        // My_list ArrayList
        My_list.Add("C");
        My_list.Add("C++");
        My_list.Add("C#");
        My_list.Add("Java");
 
        Console.WriteLine("Languages provided by GeeksforGeeks:");
        foreach(var elements in My_list)
        {
            Console.WriteLine(elements);
        }
    }
}
 
// Interface 2
interface GFG2 {
    void courses();
}
 
// Parent class 2
class Geeks2 : GFG2 {
 
    // Providing the implementation
    // of courses() method
    public void courses()
    {
 
        // Creating ArrayList
        ArrayList My_list = new ArrayList();
 
        // Adding elements in the
        // My_list ArrayList
        My_list.Add("System Design");
        My_list.Add("Fork Python");
        My_list.Add("Geeks Classes DSA");
        My_list.Add("Fork Java");
 
        Console.WriteLine("\nCourses provided by GeeksforGeeks:");
        foreach(var elements in My_list)
        {
            Console.WriteLine(elements);
        }
    }
}
 
// Child class
class GeeksforGeeks : GFG1, GFG2 {
 
    // Creating objects of Geeks1 and Geeks2 class
    Geeks1 obj1 = new Geeks1();
    Geeks2 obj2 = new Geeks2();
 
    public void languages()
    {
        obj1.languages();
    }
 
    public void courses()
    {
        obj2.courses();
    }
}
 
// Driver Class
public class GFG {
 
    // Main method
    static public void Main()
    {
 
        // Creating object of GeeksforGeeks class
        GeeksforGeeks obj = new GeeksforGeeks();
        obj.languages();
        obj.courses();
    }
}
 
 

Output:

Languages provided by GeeksforGeeks: C C++ C# Java  Courses provided by GeeksforGeeks: System Design Fork Python Geeks Classes DSA Fork Java


Next Article
C# | Type.GetInterfaces() Method
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-Inheritance
  • CSharp-Interfaces
  • CSharp-OOP

Similar Reads

  • C# | Inheritance in interfaces
    C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.Important Points: If a class implements an interface, then it is nece
    3 min read
  • C# | Multilevel Inheritance
    Introduction: In object-oriented programming, inheritance is the ability to create new classes that are derived from existing classes, known as base or parent classes. Inheritance allows the derived classes to inherit properties and methods of the base classes and to add new features or functionalit
    7 min read
  • C# | Type.GetInterfaces() Method
    Type.GetInterfaces() Method is used to get all the interfaces implemented or inherited by the current Type when overridden in a derived class. Syntax: public abstract Type[] GetInterfaces ();Return Value: This method returns an array of Type objects representing all the interfaces implemented or inh
    2 min read
  • C# Program to Implement Multiple Interfaces in the Same Class
    Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface’s members will be given by the class that implements the interface implicitly or explicitly. C# allows that a sin
    3 min read
  • C# | How to Implement Multiple Interfaces Having Same Method Name
    Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface's members will be given by the class who implements the interface implicitly or explicitly. C# allows the impleme
    4 min read
  • Demonstrating Transactions Using Interface Through C#
    The interface is a special class in which we can declare all of our methods. Here in this problem, we are going to create an interface in which we are going to declare all of the required implementations which is necessary for transaction management. Here in this article, we are going to see how rea
    2 min read
  • C# | How to use Interface References
    In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface. An interface reference variable only knows that methods which are decl
    5 min read
  • C# Program to Demonstrate Interface Implementation with Multi-level Inheritance
    Multilevel Inheritance is the process of extending parent classes to child classes in a level. In this type of inheritance, a child class will inherit a parent class, and as well as the child class also act as the parent class to other class which is created. For example, three classes called P, Q,
    3 min read
  • Type.FindInterfaces() Method in C# with Examples
    Type.FindInterfaces(TypeFilter, Object) Method is used to return an array of Type objects which represents a filtered list of interfaces implemented or inherited by the current Type. All of the interfaces implemented by this class are considered during the search, whether declared by a base class or
    3 min read
  • C# | Type.GetInterface() Method
    Type.GetInterface() Method is used to gets a specific interface implemented or inherited by the current Type. GetInterface(String) Method This method is used to search for the interface with the specified name. Syntax: public Type GetInterface (string name); Here, it takes the string containing the
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences