oop - How does using interfaces overcome the problem of multiple inheritance in C#? -


i understand c# not support multiple inheritance, , solution use interfaces instead. don't understand why interfaces doesn't create diamond problem same way multiple inheritance would. how using interfaces avoid pitfalls of multiple inheritance?

one class may implement number of interfaces, if interfaces extend other interfaces well. multiple inheritance not possible classes.

// not allowed class { void a() {} } class b { void b() {} } class c : a, b {}  // allowed interface ia { void a(); } interface ib { void b(); }  class : ia, ib {     public void a() {}     public void b() {} } 

the diamond problem exists classes because there possibility of clashing implementations (if a , b have same method , c extends both, method take?). interfaces, on other hand, require implementing type have methods declare.

if exact same method defined in 2 interfaces, , class implements both interfaces, doesn't matter. class needs provide implementation method code can written call method. meaning, works:

interface ia { void method(int x); } interface ib { void method(int x); }  class : ia, ib {     public void method(int x)     {         console.writeline(x);     } } 

note class may still inherit 1 other class, plus number of interfaces:

class : b, ia, ib {} 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -