The C# 4.0 specs read:
When a virtual method is invoked, the runtime type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a nonvirtual method invocation, the compile-time type of the instance is the determining factor.
At first, I thought this had something to do with initialization. For example, given two initializations:
BaseClass bcDerived = new Derived();
vs BaseClass bcBase = new BaseClass();
and an overload in a helper class:
public virtual void Method(Derived d)
{
Console.WriteLine("Result = derived called");
}
public virtual void Method(BaseClass d)
{
Console.WriteLine("Result = base called");
}
Method
invokation is not impacted by the virtual
keyword in this case. Regardless of having marked virtual
, the least derived overload is called. Only during override
in the Derived class does the method invocation change.
So, what do "runtime type" and "compile-time type" mean? How do they impact method invocation?
Method
is declared and how it is used. – Skywaycallvirt
instruction (in so much as I am comparing apples to oranges). I assumed the keyword is lacking in my example. After more thought you are right...it doesn't directly address the example. Thecallvirt
instruction should still exist in my example because I specified virtual. I know I'm doing a bit of an oddball thing by testing overloads. My goal is to fully understand the C# spec definintion. – Turkish