Reputation: 2070
I am trying to understand how CLR dispatches method call correctly when an object hides base class member when object reference is stored in a base class variable.
The point of my confusion is the object header created by runtime. The object header on heap has two fields: Type pointer and Sync block index. The type pointer points to the method table of the class. Even if the object reference is of base class, the object created on heap is of derived class. This should cause runtime to use method table of derived class object. But the runtime calls the base class member correctly.
Could you please help me in understanding the flow as how does CLR calls the methods correctly in this scenario?
Upvotes: 4
Views: 292
Reputation: 171246
Calling a method that is not virtual or overridden in any way has nothing to do with the method table. The C# compiler calls that method by name (the assembly really contains the name as a string!) and the JIT hard-codes the address of the function into the emitted x86 code. The address does not depend on the runtime type of the this
object reference.
Upvotes: 1
Reputation: 942348
The object type as recorded in the object header doesn't matter here. The compiler emits the method call naming the specific class whose method should be called. Quite visible in the generated IL. For example:
class Base {
void foo() { }
void callFoo() {
foo(); // <== here
}
}
class Derived : Base {
new void foo() { }
}
The indicated statement generates this IL:
IL_0002: call instance void ConsoleApplication1.Base::foo()
Note the presence of Base in the call opcode, there is no ambiguity.
Upvotes: 4