Skip to content

Instantly share code, notes, and snippets.

@toddlucas
Last active December 20, 2021 18:58
Show Gist options
  • Save toddlucas/d4887b8db9b68b01378bcb26c5348e9b to your computer and use it in GitHub Desktop.
Save toddlucas/d4887b8db9b68b01378bcb26c5348e9b to your computer and use it in GitHub Desktop.
Double dispatch example from Wikipedia in C#
// https://en.wikipedia.org/wiki/Double_dispatch
using static System.Console;
WriteLine("Example 1. Method overloading");
Asteroid theAsteroid = new();
SpaceShip theSpaceShip = new();
ApolloSpacecraft theApolloSpacecraft = new();
// Asteroid hit a SpaceShip
theAsteroid.CollideWith(theSpaceShip);
// Asteroid hit an ApolloSpacecraft (overloaded version)
theAsteroid.CollideWith(theApolloSpacecraft);
WriteLine("Example 2. Derived methods called");
ExplodingAsteroid theExplodingAsteroid = new();
// ExplodingAsteroid hit a SpaceShip (derived asteroid class called)
theExplodingAsteroid.CollideWith(theSpaceShip);
// ExplodingAsteroid hit an ApolloSpacecraft
theExplodingAsteroid.CollideWith(theApolloSpacecraft);
WriteLine("Example 3. Dynamic dispatch");
Asteroid theAsteroidReference = theExplodingAsteroid;
// ExplodingAsteroid hit a SpaceShip (override called with dynamic dispatch)
theAsteroidReference.CollideWith(theSpaceShip);
// ExplodingAsteroid hit an ApolloSpacecraft
theAsteroidReference.CollideWith(theApolloSpacecraft);
WriteLine("Example 4. Fails expectations");
SpaceShip theSpaceShipReference = theApolloSpacecraft;
// Asteroid hit a SpaceShip (but expected Asteroid hit an ApolloSpacecraft)
theAsteroid.CollideWith(theSpaceShipReference);
// ExplodingAsteroid hit a SpaceShip (but expected ExplodingAsteroid hit an ApolloSpacecraft)
theAsteroidReference.CollideWith(theSpaceShipReference);
WriteLine("Example 5. Double dispatch");
// SpaceShip theSpaceShipReference = theApolloSpacecraft;
// Asteroid theAsteroidReference = theExplodingAsteroid;
theSpaceShipReference.CollideWith(theAsteroid);
theSpaceShipReference.CollideWith(theAsteroidReference);
class SpaceShip
{
public virtual void CollideWith(Asteroid inAsteroid)
{
inAsteroid.CollideWith(this);
}
}
class ApolloSpacecraft : SpaceShip
{
public override void CollideWith(Asteroid inAsteroid)
{
inAsteroid.CollideWith(this);
}
}
class Asteroid
{
public virtual void CollideWith(SpaceShip ss)
{
WriteLine("Asteroid hit a SpaceShip");
}
public virtual void CollideWith(ApolloSpacecraft asc)
{
WriteLine("Asteroid hit an ApolloSpacecraft");
}
}
class ExplodingAsteroid : Asteroid
{
public override void CollideWith(SpaceShip ss)
{
WriteLine("ExplodingAsteroid hit a SpaceShip");
}
public override void CollideWith(ApolloSpacecraft asc)
{
WriteLine("ExplodingAsteroid hit an ApolloSpacecraft");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment