c# - Are virtual members called via reflection (in normal circumstances)? -


i testing effects of calling virtual member in constructor, , discovered when calling member resulting exception wrapped within targetinvocationexception.

according docs is:

the exception thrown methods invoked through reflection

however i'm unaware of invokations via reflection. mean virtual members called via reflection? if not why in case?

the code:

class classa     {         public classa()         {             splitthewords();         }          public virtual void splitthewords()         {             //i've been overidden         }     }  class classb : classa     {         private readonly string _output;          public classb()         {             _output = "constructor has occured";         }          public override void splitthewords()         {             string[] = _output.split(new[]{' '}); //targetinvocationexception!         }     } 

no, virtual methods called via virtual dispatch.

reflection not being used here. , nor virtual method calls. believe documentation exception misleading in exceptions of type are thrown methods invoked via reflection, not exclusively so.

if curious why code in question gives exception, because of order in constructors executed. classb constructor same as:

public classb() : base() {     _output = "constructor has occured"; } 

note call base(), calls base constructor before classb constructor run and, hence, before _output assigned. splitthewords virtual method called in base constructor, resolves classb.splitthewords. method attempts use _output, hence error.

for more detailed @ why virtual methods should not called constructors this question has useful information. eric lippert has blog post on why case here.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -