c# - What happen when you cast from an abstract to an interface? -


can explain happen behind scene when cast abstract/interface interface?
example: let abstractclasse = new concrete() , concrete implements both itext interface , abstractclasse , itext = (itext)a.

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks;  namespace consoleapplication1 {     class program     {         interface itext         {             string totext();         }         class subtip : subtitleformat, itext         {             public int error { get; set; }              public subtip(int error)             {                 error = error;             }             public string totext()             {                 return $"{error}, hello!";             }         }         abstract class subtitleformat         {             protected int _errorcount = 1;              public int errorcount             {                                 {                     return _errorcount;                 }             }         }         static void main(string[] args)         {             subtitleformat sb = new subtip(10);             itext sb2 = sb itext;              console.writeline(sb.errorcount);             console.writeline((sb subtip).error);             console.writeline(sb2.totext());             console.readline();         }     } } 

when cast interface or class proper type of object in question used determine whether compatible target. largely irrelevant object typed - object, interface, final class or base class.

so, instance, can this:

subtitleformat sb = new subtip(10); itext sb2 = sb itext; subtip sb3 = sb2 subtip; 

both of conversions valid, @ end of sb3 have non-null value. 3 variables (sb, sb2 , sb3) refer same object, object.referenceequals(sb, sb3) true.

because true type of object instance used determine whether or not cast work, won't work:

public class notitext : subtitleformat {     public string totext()     {         return "";     } }  static void main(string[] args) {     subtitleformat sb = new notitext();     itext sb2 = sb itext; } 

Comments