Multimethods in C#

I read a couple of interesting articles on the subject of multiple dispatch last night. The first, entitled Visitor Pattern Considered Useless, starts by describing the visitor design pattern with particular emphasis on how it can enable the definition of new operations on a hierarchy of types without having to modify the hierarchy's classes themselves. It gave a quick overview and then moved on to a critique of the pattern and segued into a description of the multimethod implementation provided by Nice which is a very interesting Java-like (and hence C#-like) object-oriented programming language. This got me thinking about playing around with the idea of multiple dispatch in C#. Check out the attachment containing a sample project I hacked together or view the main class here.

Note the following:

  • Basically, it performs overload resolution of generic methods at runtime as opposed to C#'s usual overload resolution which is performed at compile time.
  • It's based heavily around delegates.
  • It determines the "most compatible" method based on a measure of "generality" of parameter types compared to actual argument types.
  • Currently it only handles methods that take "in" parameters. It doesn't do "out" or "ref" and doesn't support return values yet.
  • The code is not performant: currently all the runtime overload resolution is done through multiple "for" loops over the parameter and argument type arrays. I'm sure some DLR-type magic could be employed instead to improve the performance of this area of the code.
  • This code is incredibly rough around the edges.
  • It's a work in progress.

If there are any other dynamic programmers in C# interested in this kind of thing, then let me know!

MultipleDispatch.zip

Comments