Free mag vol1 | Page 669

CHAPTER 16  DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME try { // Get metadata for the SimpleMath type. Type math = asm.GetType("MathLibrary.SimpleMath"); // Create a SimpleMath on the fly. object obj = Activator.CreateInstance(math); // Get info for Add. MethodInfo mi = math.GetMethod("Add"); // Invoke method (with parameters). object[] args = { 10, 70 }; Console.WriteLine("Result is: {0}", mi.Invoke(obj, args)); } catch (Exception ex) { Console.WriteLine(ex.Message); } } Now, consider the simplification of the previous logic with the dynamic keyword, via the following new method: private static void AddWithDynamic() { Assembly asm = Assembly.Load("MathLibrary"); try { // Get metadata for the SimpleMath type. Type math = asm.GetType("MathLibrary.SimpleMath"); // Create a SimpleMath on the fly. dynamic obj = Activator.CreateInstance(math); Console.WriteLine("Result is: {0}", obj.Add(10, 70)); } } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { Console.WriteLine(ex.Message); } Not too shabby! If you call both methods from the Main() method, you’ll see identical output. However, when using the dynamic keyword, you saved yourself quite a bit of work. With dynamically defined data, you no longer need to manually package up arguments as an array of objects, query the assembly metadata, or other such details. If you are building an application that makes heavy use of dynamic loading/late binding, I am sure you can see how these code savings would add up over time. 611