If you want to have really dynamic resolution, then you have to use dynamic
keyword, like so:
static void Main(string[] args)
{
dynamic ship = new SpaceShip();
Planet planet = new Planet();
ship.Visit(planet); // => Specific
// also
GenericPlanet genericPlanet = new GenericPlanet();
ship.Visit(planet); // Generic
}
In this case behaviour will be something like you have described - type of the parameter matters. But what you most likely want is to have a method override, like so:
class GenericSpaceShip
{
public virtual void Visit(GenericPlanet planet)
{
Console.WriteLine("Generic");
}
}
class SpaceShip : GenericSpaceShip
{
public override void Visit(GenericPlanet planet)
{
Console.WriteLine("Specific");
}
}
In this case the Specific method will be called if you have an instance of SpaceShip
and Generic method for instance of GenericSpaceShip
, regardless of planet type. In this case type of the ship matters:
static void Main(string[] args)
{
SpaceShip ship = new SpaceShip();
Planet planet = new Planet();
ship.Visit(planet); // => Specific
// also
GenericPlanet genericPlanet = new GenericPlanet();
ship.Visit(planet); // Specific
}
You would always get Generic
if GenericSpaceShip
was used instead.