Dynamic dispatch in C#

Charlie Calvert blogged about dynamic support in C# 4.0. I love this for two reasons. One it will enable dynamic language interop and COM automation interop in a much better way, and two it will use the DLR. So if you were writing COM automation interop before this is what you would have had to write:

 Type myType = Type.GetTypeFromProgID("IMyLib.MyClass");
object obj = Activator.CreateInstance(myType);
object[] args = new object[2];
args[0] = "Hello";
args[1] = 3;
myType.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, args);

Now you will probably write something like this:

 Type myType = Type.GetTypeFromProgID("IMyLib.MyClass");
dynamic
{
    object obj = Activator.CreateInstance(myType);
    obj.MyMethod("Hello", 3);
}

If they use the DLR this will probably generate a dynamic site underneath to invoke the method. Essentially the DLR will probably create a delegate which will in effect do the invoke. For a simple case of making one call this might not boost perf but if the same method is used with different params etc. we should see better perf. (For an explanation of dynamic sites read Martin's posts on the topic). (Again this is all conjecture - I don't know how the C# team is going to design it). But more than perf I think the value is in the ease of use. This should pave the way for interop with IronPython/ IronRuby.

I find the syntax a little cumbersome though. Creating and using the dynamic variables will have to be right next to each other. While that might make the code a lot more readable I doubt if it would be practical. I would definitely like to make calls to strongly typed-apis in-between. I prefer the other syntax that a lot of people in the comments section have suggested - annotate the object definition with a keyword or an attribute. Ofcourse that creates its own readability mess. It won't be readily apparent if a call is dyamic or static. But I would argue we already have a similar mess with extension methods. Maybe a different operator can be used for invocation?