Can we inherit child class from 2 base classes? if yes then how? If not then why?
Multiple inheritance refers to the scenario in which a class inherits from more than one class. However, in C#, this form of multiple inheritance is not permitted. If an attempt is made to inherit a class from two different classes, the C# compiler will generate an error message.
Imagine having a touchscreen mobile device with features from both 'Samsung' and 'Nokia'. If an attempt is made to inherit from both the Samsung and 'Nokia' classes, a compile-time error will be displayed.
If yes then How?
In C#, the concept of multiple inheritance can be realized through the use of interfaces. It's possible to implement multiple interfaces within a single class.
As illustrated in the previous diagram, it's clear that a class cannot inherit from two classes simultaneously. Therefore, the approach we'll take is to create interfaces representing Samsung and Nokia functionalities. Subsequently, these interfaces will be implemented within the TouchMobile class.
interface INokia
{
void PlayGameWithNokia();
}
interface ISamsung
{
void PlayGameWithSamsung();
}
public class TouchMobile : ISamsung, INokia
{
public void PlayGameWithNokia()
{
Console.WriteLine("PlayGameWithNokia");
}
public void PlayGameWithSamsung()
{
Console.WriteLine("PlayGameWithSamsung");
}
}
class Program
{
static void Main(string[] args)
{
//Here we have somehow achieved multiple inheritance by using implementation of interfaces.
TouchMobile obj = new TouchMobile();
obj.PlayGameWithNokia();
obj.PlayGameWithSamsung();
}
}
If not then why?
We cannot inherit multiple classes with one class, the situation is that there is confusion that which class member is inherited if both parent classes have the same member name.
Due to this situation C# doesn’t support multiple inheritance and throws the compile time error. So it’s clear that it is quite difficult to achieve multiple inheritance in C# but we can do it by using interfaces.