CHAPTER 16 DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME
By declaring the obj variable using the dynamic keyword, the heavy lifting of reflection is done on
your behalf, courtesy of the DRL.
Leveraging the dynamic Keyword to Pass Arguments
The usefulness of the DLR becomes even more obvious when you need to make late-bound calls on
methods that take parameters. When you use “longhand” reflection calls, arguments need to be
packaged up as an array of objects, which are passed to the Invoke() method of MethodInfo.
To illustrate using a fresh example, begin by creating a new C# Console Application named
LateBindingWithDynamic. Next, add a Class Library project to the current solution (using the File Add
New Project... menu option) named MathLibrary. Rename the initial Class1.cs of the MathLibrary
project to SimpleMath.cs, and implement the class like so:
public class SimpleMath
{
public int Add(int x, int y)
{
return x + y;
}
}
After you have compiled your MathLibrary.dll assembly, place a copy of this library in the
\bin\Debug folder of the LateBindingWithDynamic project (if you click the Show All Files button for each
project of the Solution Explorer, you can simply drag and drop the file between projects). At this point,
your Solution Explorer should look something like Figure 16-4.
609