CHAPTER 16 DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME
HELLO
'string' does not contain a definition for 'toupper'
Of course, the process of wrapping all dynamic method invocations in a try/catch block is rather
tedious. As long as you watch your spelling, and parameter passing, this is not required. However,
catching exceptions is handy when you might not know in advance if a member will be present on the
target type.
The Scope of the dynamic Keyword
Recall that implicitly typed data (declared with the var keyword) is only possible for local variables in a
member scope. The var keyword can never be used as a return value, a parameter, or a member of a
class/structure. This is not the case with the dynamic keyword however. Consider the following class
definition:
class VeryDynamicClass
{
// A dynamic field.
private static dynamic myDynamicField;
// A dynamic property.
public dynamic DynamicProperty { get; set; }
// A dynamic return type and a dynamic paramater type.
public dynamic DynamicMethod(dynamic dynamicParam)
{
// A dynamic local variable.
dynamic dynamicLocalVar = "Local variable";
int myInt = 10;
}
}
if (dynamicParam is int)
{
return dynamicLocalVar;
}
else
{
return myInt;
}
You could now invoke the public members as expected; however, as you are operating on dynamic
methods and properties, you cannot be completely sure what the data type will be! To be sure, the
VeryDynamicClass definition might not be very useful in a real-world application, but it does illustrate the
scope of where you can apply this C# keyword.
604