So basically, I want to understand what are the general steps that the C # compiler takes to determine if the method that is being called is not a virtual instance method or a virtual method.
The confusion comes from these two explanations (CLR through 3rd Edition C #, Jeffrey Richter, Fundamentals of Chapter 4)
When invoking a non-virtual instance method, the JIT compiler finds a type object that matches the type of the variable being used to call
And for virtual method calls
When invoking a virtual instance method, the JIT compiler generates some additional code in the method, which will be executed every time the method is called. This code will first look in the variable used to make the call, and then follow the address of the caller
I created a small test project
class Program { static void Main(string[] args) { Parent p = new Derived(); p.Foo(10);
While Jon Skeet has a blog post explaining why the program produces these outputs, and Eric Lippert confirms that in his blog post (check the comment section), I still canβt understand how the compiler decides is whether the method that is being called is not a virtual instance method or a virtual method.
It seems that when calling the nonvirtual method of the instance, the compiler checks the type of the variable used to call the method, and for virtual methods, the type of the object referenced by the variable that is used to call the method, so I think there should be some way to determine whether the method is not virtual or virtual before deciding how to execute the method.
source share