Datasheet

772
Programming Dynamically
Other benefits to dynamic languages in general show up as you use them
more. For instance, macro languages are usually dynamically typed. If you
have tried to build macros in previous versions of Visual Studio, you know
what a pain it is to use a static language.
Making C# (and VB.NET, for that matter) more dynamic not only makes it a
better language for extending Visual Studio, but it also gives programmers
the capability to include the language in the programs they write so that
other developers can further extend those applications.
Programming Dynamically
By now, you must be asking, “What exactly are we talking about here?” Fair
question. When you define a new variable, you can use the dynamic keyword,
and C# will let you make assumptions about the members of the variable.
More or less, what I’m talking about it this. If you want to declare a new
Course object, you do it like this:
Course newCourse = new Course();
newCourse.Schedule();
This is, of course, assuming that you have a Course class defined somewhere
else in your program, like this:
class Course {
public void Schedule()
{
//Something fancy here
}
}
But what if you don’t know what class the new object will be? How do you
handle that? You could declare it as an Object, because everything derives
from Object, right? Here’s the code:
Object newCourse = new Object();
Not so fast, my friend, if you make your next line this:
newCourse.Schedule();
Note the squiggly line appears almost immediately, and you get the famous
“object does not contain a definition for Schedule...” error in the design time
Error List.
53_563489-bk08ch01.indd 77253_563489-bk08ch01.indd 772 3/19/10 8:17 PM3/19/10 8:17 PM