I saw some comments on forums, and it seems that people want to be able to inherit from multiple classes in c#. Why would you ever need this? I can't think of any use for this, but since there's people that want it, there's got to be some.
Multiple inheritance is useful when a subclass needs to combine multiple contracts and inherit some, or all, of the implementation of those contracts. For example, the AmericanStudent class needs to inherit from both the Student class and the American class. But multiple inheritance imposes additional difficulties.
You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance.
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class.
Which of the following advantages we lose by using multiple inheritances? Explanation: The benefit of dynamic binding and polymorphism is that they help making the code easier to extend but by multiple inheritance it makes harder to track.
Well, here's an ASP.NET WebForms example:
I have one base class, a web control, let's say it is a simple TextBox
.
I then inherit from the TextBox
to provide formatting - RichTextBox
.
I then want to have a TextBox
that can spell-check - SpellCheckingTextBox
.
What if I need a SpellCheckingRichTextBox
? I would have to implement the spell checking or rich text logic again and inherit from one or the other.
In reality you would define them as interfaces: ISpellCheckingTextBox
and IRichTextBox
and implement them in a SpellCheckingRichTextBox
. You could also write extension methods for TextBox
to accomplish the same thing.
Multiple inheritance is fundamentally flawed because it views inherited classes as equal. What if both base classes had an ID
field?
People probably want to do this because they are accustomed to doing it in C++. It isn't allowed in C#. Which, IMO, is a good thing, from an application maintainability point of view. Often times, using multiple interfaces will accomplish the same thing.n
If you have a base class with abstract methods properly designed and it's know that the inheriting object will only need the methods defined in that class, you have have a valid design pattern that doesn't require MI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With