C# | Multiple inheritance using interfaces
Last Updated :
06 Apr, 2023
Introduction:
- 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
- multiple inheritance using interfaces. An interface is a collection of abstract methods that a class can implement to provide specific behavior. A class can
- implement multiple interfaces, which allows it to inherit functionality from multiple sources.
Advantages:
- Flexibility: Multiple inheritance using interfaces provides a flexible way to add functionality to a class without inheriting implementation details from a base class.
- Code reuse: By implementing multiple interfaces, a class can reuse code from multiple sources, making it easier to write efficient and maintainable code.
- Separation of concerns: Multiple inheritance using interfaces promotes the separation of concerns, making it easier to understand and maintain the code.
Disadvantages:
- 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.
- 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.
- 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());
}
}
OutputArea 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:
- Allows a class to inherit from multiple sources, providing more flexibility in creating class hierarchies.
- Interfaces enforce a contract that implementing classes must adhere to, promoting consistency and predictability in the codebase.
- Interfaces allow for a separation of concerns, allowing for more modular and reusable code.
The disadvantages of multiple inheritance through interfaces include:
- The need for more boilerplate code, as interfaces require implementing classes to provide their own implementation for each method.
- Multiple inheritance can make the class hierarchy more complex and harder to understand.
- 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:
- C# 9.0 in a Nutshell: The Definitive Reference by Joseph Albahari and Ben Albahari
- Pro C# 9 with .NET 5: With Visual Studio 2019 by Andrew Troelsen and Philip Japikse
- 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 by Mark J. Price.
Reference books:
- "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
- "C# in a Nutshell: The Definitive Reference" by Joseph Albahari and Ben Albahari
- "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
Similar Reads
C# Tutorial C# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET Framework The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# Interview Questions and Answers C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications.Her
15+ min read
C# Dictionary Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of a Dictionary is, that it is a generic type. A dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature mean
5 min read
C# List Class In C#, the List<T> class represents the list of objects that can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings, etc. List<T> class also provides the methods to search,
7 min read
C# Delegates A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form application),
6 min read
ASP.NET Interview Questions and Answer ASP.NET is a popular framework by Microsoft for building fast and scalable web applications. It allows developers to create dynamic websites, services, and apps, using server-side code and offering a user-friendly experience. Trusted by companies like Microsoft, Dell, and Accenture, ASP.NET is used
15+ min read
C# .NET Framework (Basic Architecture and Component Stack) C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Data Types Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# Arrays An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read