I’ve been reading documentation about virtual methods :
In a virtual method invocation, the run-time type of the instance for
which that invocation takes place determines the actual method
implementation to invoke. In a non-virtual method invocation, the
compile-time type of the instance is the determining factor. In
precise terms, when a method named N is invoked with an argument list
A on an instance with a compile-time type C and a run-time type R
(where R is either C or a class derived from C), the invocation is
processed as follows… :
http://msdn.microsoft.com/en-us/library/aa645767(v=vs.71).aspx
However, I noticed something which is bold above. Lets say we have a code like this:
class Planet{
public string Name;
public float Size;
public virtual void SpinPlanet(){
Console.WriteLine("Hoooraaay!!!");
}
}
class Earth : Planet{
}
And somewhere in my code I do:
Earth world = new Earth();
world.SpinPlanet();
In this case:
- N is
SpinPlanet() - C is
Earth - R is
Planet
So how come R can be derived class of compile-time type C. Aren’t the base class types being resolved during run-time?
You are mistaken- the compile-time type (C) is
Earthand the run-time type (R) is alsoEarth. The part of the specification that you point out is not really relevant here.What is relevant is http://msdn.microsoft.com/en-us/library/aa691356(v=vs.71).aspx, specifically:
The only candidate implementation of
SpinPlanetjust happens to be in the base class ofEarth, not in the derived class.The part of the spec that you refer to would apply if the code were:
(especially if Earth defined an override for
SpinPlanet) because then the compile type (the type of the variable) would bePlanet, but the runtime type would beEarth.