Are virtual members called through reflection (under normal circumstances)?

I tested the effects of invoking a virtual member in the constructor and found that when this member was called, the resulting exception was wrapped in a TargetInvocationException .

According to the docs, this is:

Exception thrown by methods called by reflection

However, I do not know about any challenges through reflection. Does this mean that virtual members are always invoked through reflection? If not, why is this the 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[] something = _output.Split(new[]{' '}); //TargetInvocationException! } } 
+6
source share
2 answers

No, virtual methods are called through virtual dispatch .

Reflection is not used here. And for no virtual method calls. I believe that the documentation for the exception is a little misleading in the fact that exceptions of this type are generated by reflection-induced methods, but not exclusively.

If someone is wondering why the code in the question gives an exception, this is because of the order in which the constructors are executed. ClassB constructor is the same as:

 public ClassB() : base() { _output = "Constructor has occured"; } 

Note the call to base() , it calls the base constructor before starting the ClassB constructor and, therefore , before _output is assigned . The virtual SplitTheWords method SplitTheWords called in the base constructor, which allows ClassB.SplitTheWords . This method tries to use _output , therefore an error.

A more detailed look at why virtual methods should not be called from designers by this SO question contains some useful information. Eric Lippert also has a very good blog post about why this is happening here .

+5
source

Are virtual members called through reflection (under normal conditions)?

NOT.

Not from the constructor, so something else happens. This will help you see the code that calls the code you showed and the stack trace from the exception.

0
source

Source: https://habr.com/ru/post/919679/


All Articles