CHAPTER 16 DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME
s1 is of type: System.String
s2 is of type: System.String
s3 is of type: System.String
What makes a dynamic variable much (much) different from a variable declared implicitly or via a
System.Object reference is that it is not strongly typed. Said another way, dynamic data is not statically
typed. As far as the C# compiler is concerned, a data point declared with the dynamic keyword can be
assigned any initial value at all, and can be reassigned to any new (and possibly unrelated) value during
its lifetime. Consider the following method, and the resulting output:
static void ChangeDynamicDataType()
{
// Declare a single dynamic data point
// named "t".
dynamic t = "Hello!";
Console.WriteLine("t is of type: {0}", t.GetType());
t = false;
Console.WriteLine("t is of type: {0}", t.GetType());
}
t = new List();
Console.WriteLine("t is of type: {0}", t.GetType());
t is of type: System.String
t is of type: System.Boolean
t is of type: System.Collections.Generic.List`1[System.Int32]
Now, at this point in your investigation, do be aware that the previous code would compile and
execute identically if you were to declare the t variable as a System.Object. However, as you will soon
see, the dynamic keyword offers many additional features.
Calling Members on Dynamically Declared Data
Now, given that a dynamic data type can take on the identity of any type on the fly (just like a variable of
type System.Object), the next question on your mind might be about calling members on the dynamic
variable (properties, methods, indexers, register with events, etc.). Well, syntactically speaking, it will
again look no different. Just apply the dot operator to the dynamic data variable, specify a public
member, and supply any arguments (if required).
However (and this is a very big “however”), the validity of the members you specify will not be
checked by the compiler! Remember, unlike a variable defined as a System.Object, dynamic data is not
statically typed. It is not until runtime that you will know if the dynamic data you invoked supports a
specified member, if you passed in the correct parameters, spelled the member correctly, and so on.
Thus, as strange as it might seem, the following method compiles perfectly:
static void InvokeMembersOnDynamicData()
{
dynamic textData1 = "Hello";
601