CHAPTER 16 DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME
// This would be a compile-time error!
// a = "Hello";
}
Using implicit typing simply for the sake of doing so is considered by many to be bad style (if you
know you need a List, just declare a List). However, as you have seen in Chapter 12, implicit
typing is very useful with LINQ, as many LINQ queries return back enumerations of anonymous class
(via projections) which you cannot directly declare in your C# code. However, even in such cases, the
implicitly typed variable is, in fact, strongly typed.
On a related note, as you learned back in Chapter 6, System.Object is the topmost parent class in the
.NET framework, and can represent anything at all. Again, if you declare a variable of type object, you
have a strongly typed piece of data; however, what it points to in memory can differ based on your
assignment of the reference. In order to gain access to the members the object reference is pointing to in
memory, you need to perform an explicit cast.
Assume you have a simple class named Person that defines two automatic properties (FirstName and
LastName) both encapsulating a string. Now, observe the following code:
static void UseObjectVarible()
{
// Assume we have a class named Person.
object o = new Person() { FirstName = "Mike", LastName = "Larson" };
}
// Must cast object as Person to gain access
// to the Person properties.
Console.WriteLine("Person's first name is {0}", ((Person)o).FirstName);
With the release of .NET 4.0, the C# language introduced a keyword named dynamic. From a high
level, you can consider the dynamic keyword a specialized form of System.Object, in that any value can
be assigned to a dynamic data type. At first glance, this can appear horribly confusing, as it appears you
now have three ways to define data whose underlying type is not directly indicated in our code base. For
example, this method:
static void PrintThreeStrings()
{
var s1 = "Greetings";
object s2 = "From";
dynamic s3 = "Minneapolis";
Console.WriteLine("s1 is of type: {0}", s1.GetType());
Console.WriteLine("s2 is of type: {0}", s2.GetType());
Console.WriteLine("s3 is of type: {0}", s3.GetType());
}
would print out the following if invoked from Main():
600