Why was C# designed this way, and what are the disadvantages of being able to derive from unlimited classes? (I know you can use interfaces for most cases)
-
https://stackoverflow.com/questions/2456154/does-c-sharp-support-multiple-inheritance – Amit Kumar Singh Aug 30 '17 at 01:01
2 Answers
Multiple inheritence leads to the Diamond Problem.
The "diamond problem" (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
For example, in the context of GUI software development, a class Button may inherit from both classes Rectangle (for appearance) and Clickable (for functionality/input handling), and classes Rectangle and Clickable both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an overridden equals method in Rectangle or Clickable (or both), which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.
Also, from the c# dev team:
The number of places where MI is truly appropriate is actually quite small. In many cases, multiple interface inheritance can get the job done instead. In other cases, you may be able to use encapsulation and delegation. If we were to add a slightly different construct, like mixins, would that actually be more powerful?
Multiple implementation inheritance injects a lot of complexity into the implementation. This complexity impacts casting, layout, dispatch, field access, serialization, identity comparisons, verifiability, reflection, generics, and probably lots of other places.
Link.
Highly opinionated answer...because things can get funky.
public class Goose
{
public Wings MyWings {get;set;}
public void Eat()
{
//.. eat before flying
}
public void Fly()
{
//.. flap wings
}
}
public class Airplane
{
public Engine MyEngine {get;set;}
public void FuelUp ()
{
//.. fuel up before flying
}
public void Fly()
{
//.. start engine and accelerate
}
}
public class SpruceGoose: Goose, Airplane
{
public void SomeMethod()
{
this.Fly(); // do I flap my wings?
// or do I start my engine and accelerate
// or do I do both? which one first
// do I eat? or do I fuel up?
}
}

- 546
- 3
- 7