Using dynamic dispatch instead of reflection to call methods

By Indranil Chatterjee

With the introduction of the Dynamic Language Runtime (and the dynamic keyword in C#), coding can be reduced for many cases and one such scenario is invoking methods on types using reflection.

Let's say I need to invoke the method AppendFormat on the StringBuilder class, but, using reflection.
This is how I would do that using traditional reflection:

var type = Type.GetType("System.Text.StringBuilder");
var instance = Activator.CreateInstance(type);
type.GetMethod("AppendFormat", new[] { typeof(string), typeof(object) })
.Invoke(instance, new Object[] { "Hello Indranil {0}", Environment.NewLine });

Console.WriteLine(type.GetMethod("ToString", Type.EmptyTypes).Invoke(instance, null));

And this is how it can be done using dynamic dispatch:
dynamic instance = Activator.CreateInstance(Type.GetType("System.Text.StringBuilder"));
instance.AppendFormat("Hello Indranil {0}", Environment.NewLine);


The keyword dynamic in the declaration for the variabl instance instructs the compiler not to enforce type checking and so the method call AppendFormat is not evaluated until runtime, which is guaranteed to be present, given that instance is actually of type System.Text.StringBuilder.

Using dynamic dispatch instead of reflection to call methods  (1103 Views)