Visitor Pattern In C# 4.0

I’ve blogged about the Visitor pattern previously and using double dispatch to resolve .NET’s inherent inability to resolve methods by parameter type at runtime.

As I was reading about C# 4.0’s dynamic types, I started to wonder if this would mean that we could finally get a more concise implementation of the pattern.  My hunch was correct.

Here is the updated code listing (key changes bolded):

Here is the output:

Wow, just when I thought dynamic was going to suck 😀

What is somewhat interesting is that both collections have to be declared of type dynamic; I’m still mulling this over, but it’s not clear why it doesn’t work if only one of the collections is declared dynamic (I figured that it should have worked if the visitors collection alone was declared dynamic).

You may also like...