.NET Inside Out Part 14 — Calling virtual method without dynamic dispatch

This is the fourteenth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

We know that when we call virtual method we get runtime polymorphism, dynamic dispatch. Can we somehow call a method method without resolving overriding hierarchy? Or even better, by specifying which override to use?

When we call instance method, internally callvirt instruction is used. That instruction performs null check and calls method using dynamic dispatch. However, there is another instruction, used for calling methods when no dynamic dispatch is needed. It’s called call. We can generate some code and use this instruction to call the method directly. See this code:

We have three classes in our hierarchy. We create an instance of the Derived2, assign it to a variable of type Base and we would like to call the method “in the middle”, from Derived.

We wrap the method using lambda. That way we can explain which method we would like to call (and which parameters to use) but we don’t actually call it. We also use generic type parameter to specify a class with implementation of the method we would like to use.

First, we check if lambda is of correct form (line 17). Next, we evaluate arguments (line 22) and find correct method to call using the reflection (line 23). Then, we just create a generic instance of the helper method and create the lambda.

We load the instance (line 35), next, we load all arguments (and unbox them if needed) (lines 36-46). Finally, we call the method and return from the function. Ultimately, we just need to create the lambda (line 49) and return it.

Then, we call the method in line 25 and we are done. Output:

Notice, that it works correctly even if we remove override from Derived class.