I always thought C# resolves method calls dynamically during runtime by looking at the runtime type of the method call receiver (i.e. the object before the dot).
However the following code sample works differently. If I use GenericSpaceShip in the code it returns "Generic"; if I use SpaceShip it returns "Specific". Note that the runtime type in both cases is SpaceShip.
So my question is: How does C# resolve the Visit method call and why does it look at the compile time rather than the runtime type in this situation?
Note that the two Visit methods have different parameters. As Patko points out, this means I cannot use virtual/override here.
class GenericSpaceShip
{
public void Visit(GenericPlanet planet)
{
Console.WriteLine("Generic");
}
}
class SpaceShip : GenericSpaceShip
{
public void Visit(Planet planet)
{
Console.WriteLine("Specific");
}
}
class GenericPlanet { }
class Planet : GenericPlanet { }
class Starter
{
static void Main(string[] args)
{
// SpaceShip ship = new SpaceShip();
GenericSpaceShip ship = new SpaceShip();
Planet planet = new Planet();
ship.Visit(planet); // => Generic
}
}