Is C# a single dispatch or multiple dispatch language?

OK, I understood the subtle difference where function overloading is different from multiple-dispatch.

Basically, the difference is whether which method to call is chosen at run-time or compile-time. Now, I know everybody’s said this, but without a clear example this sounds VERY obvious, given that C# is statically typed and multiple-dispatch languages (apparently to me, at least) seem to be dynamically typed. Up to now, with just that definition multiple-dispatch and function overloading sounded exactly the same to me.

The case where this makes a real difference is when you

  • have two overloads of a method that differ on the type of a parameter (CaptureSpaceShip(IRebelAllianceShip ship) and CaptureSpaceShip(Xwing ship)
  • the two types (IRebelAllianceShip and CaptureSpaceShip) are polymorphic, and
  • you call the method with a reference declared as the higher type, which actually points to an object of the lower type

Full Example:

int CaptureSpaceShip(IRebelAllianceShip ship) {}
int CaptureSpaceShip(XWing ship) {}

void Main() { 
  IRebelAllianceShip theShip = new XWing();
  CaptureSpaceShip(theShip);
}

XWing obviously implements IRebelAllianceShip.
In this case, the first method will be called, whereas if C# implemented multiple-dispatch, the second method would be called.

Sorry about the doc rehash… This seems to me the clearest way to explain this difference, rather than just reading the definitions for each dispatch method.

For a more formal explanation:
http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading

Leave a Comment