CHAPTER 16 DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME
The Role of the Microsoft.CSharp.dll Assembly
When you create a new Visual Studio C# project, you will automatically have a reference set to an
assembly named Microsoft.CSharp.dll (you can see this for yourself by looking in the References folder
of the Solution Explorer). This library is very small, and defines only a single namespace
(Microsoft.CSharp.RuntimeBinder) with two classes (see Figure 16-2).
Figure 16-2. The Microsoft.CSharp.dll assembly
As you can tell by their names, both of these classes are strongly typed exceptions. The most
common class, RuntimeBinderException, represents an error that will be thrown if you attempt to invoke
a member on a dynamic data type, which does not actually exist (as in the case of the toupper() and
Foo() methods). This same error will be raised if you specify the wrong parameter data to a member that
does exist.
Because dynamic data is so volatile, whenever you are invoking members on a variable declared
with the C# dynamic keyword, you could wrap the calls within a proper try/catch block, and handle the
error in a graceful manner, like so:
static void InvokeMembersOnDynamicData()
{
dynamic textData1 = "Hello";
}
try
{
Console.WriteLine(textData1.ToUpper());
Console.WriteLine(textData1.toupper());
Console.WriteLine(textData1.Foo(10, "ee", DateTime.Now));
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
If you call this method again, you will find the call to ToUpper() (note the capital T and U) works
correctly; however, you then find the error data displayed to the console:
603