C#: Why must we explicitly cast a class to an interface to access the class's non-ambiguous implemented methods? -


here classes , interfaces have:

public interface baz {     void somemethod(); } public interface foo {     void somemethod(); } public class bar : foo {     void foo.somemethod(){} } 

question 1) possible remove foo interface bar object, or add baz interface bar object during runtime possible?

if yes, can have short code sample on how done?

if no, kindly proceed question 2 , 3.


question 2) why c# not give compile error when casting object interface not implement? if answer question 1 no, mybar never baz, why there no compiler error?

void myfunction(){     bar mybar = new bar();     (mybar baz).somemethod(); } 

question 3) why doesn't c# allow me call somemethod bar object without casting foo, if knows somemethod not ambiguous?

void myfunction(){     bar mybar = new bar();     mybar.somemethod();//doesn't work     mybar.foo.somemethod();//doesn't work (c# , give compile error if bar has property or public variable same name interface implements allow syntax)     (mybar foo).somemethod();//works though somemethod not ambiguous.     //the problem keyword "as" has option return null, want assured never case. } 

1) no, isn't

2) because can this:

public class bar2 : bar, baz {     .... }  void myfunction(){     bar mybar = someconditionunknownatcompiletime? new bar2(): new bar();     (mybar baz).somemethod(); } 

3)

void myfunction(){     bar mybar = new bar();      // method unavailable without casting 'foo' - can have      // many interfaces implemented , can have 'somemethod' defined     mybar.somemethod();      // there no field/property 'foo' defined in `bar`     mybar.foo.somemethod();      // ok     (mybar foo).somemethod();  } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -