I understand that C# does not support multiple inheritance, and that the solution is to use interfaces instead. But what I don’t understand is why interfaces doesn’t create the diamond problem the same way as multiple inheritance would. How does using interfaces avoid the pitfalls of multiple inheritance?
I understand that C# does not support multiple inheritance, and that the solution is
Share
One class may implement any number of interfaces, even if those interfaces extend other interfaces as well. Multiple inheritance is not possible only with classes.
The diamond problem exists with classes because there is a possibility of clashing implementations (if
AandBhave the same method andCextends both, which method does it take?). Interfaces, on the other hand, simply require an implementing type to have the methods that they declare.If the exact same method is defined in two interfaces, and a class implements both interfaces, that doesn’t matter. All the class needs to do is provide an implementation for the method so that code can be written to call that method. Meaning, this works:
Note that a class may still inherit from one other class, plus any number of interfaces: