tags:

views:

131

answers:

4

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.

+1  A: 

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.

Randy Minder
Very few people actually use MI in C++. Really, people want to use MI because they don't know how to do it the correct way.
BlueRaja - Danny Pflughoeft
+1  A: 

Multiple inheritance was sometimes used in C++ (and other languages) to allow a class to inherit properties and code from multiple base classes. When you have interfaces, like in C# and Java, there really is no need for multiple inheritance, so it was not implemented in those languages.

Here's a good article on multiple inheritance in Eiffel:

http://archive.eiffel.com/doc/manuals/technology/bmarticles/joop/multiple.html

Philippe Leybaert
"No need" is overstrong: yes, interfaces do most of what MI provides, but mixins provide a powerful idioms for combining orthogonal behavioural policies. Whether that power is worth the troubles of the "diamond of death" is another issue entirely.
Pontus Gagge
+3  A: 

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?

David Neale
A: 

One legitimate case for wanting it in C# is to make a derived object MarshalByRef. For example, say I want to do the following:

public class FooCorpClass
{
  // This class is defined in a 3rd party library and thus can't be changed
}

public class MyFoo : FooCorpClass, MarshalByRef
{
  // I can't do this because MarshalByRef isnt' an interface
}

Personally I see it as a shame that you can't have multiple inheritance if there aren't collisions, or have a collision handling mechanisms, but them's the breaks.

Hounshell