Datasheet
774
Putting Dynamic to Use
What happens if newCourse comes back as something that doesn’t have a
Schedule method? You get a runtime error. But there are try/catch blocks
for runtime errors. Nothing will help it compile without the dynamic keyword.
Readers who are long-time Visual Basic programmers, or even newer VB.NET
programmers, realize that you can handle this dynamically — and have
always been able to — in Visual Basic. For a long time, I have recommended
that programmers working with legacy systems use Visual Basic for their
new code, and this is exactly why.
In the interest of language parity, now C# can do it, too. In general, this is
good, because many organizations are writing legacy code in VB and new
code in C# — and it can get pretty messy in the trenches. This change makes
the code base slimmer.
Putting Dynamic to Use
When C# encounters a dynamic typed variable, like the variables we created
earlier, it changes everything that variable touches into a dynamic operation.
This dynamic conversion means that when you use a dynamically typed
object in an expression, the entire operation is dynamic.
Classic examples
There are six examples of how this works. Say we have the dynamic vari-
able dynaVariable. Because the dynamic variable will pass through all six
examples, they will all be dispatched dynamically by the C# compiler. Here
are those examples, with nods to Daniel Ng.
✦ dynamicVariable.someMethod(“a”, “b”, “c”);: The compiler
binds the method someMethod at runtime, since dynaVariable is
dynamic. No surprise.
✦ dynamicVariable.someProperty = 42;: The compiler binds the
property someProperty just like it did in the first method.
✦ var newVar = dynamicVariable + 42;: The compiler looks for any
overloaded operators of “+” with a type of dynamic. Lacking that, it out-
puts a dynamic type.
✦ int newNumber = dynamicVariable;: This is an implicit conversion
to int. The runtime determines if a conversion to int is possible. If not,
it throws a type mismatch error.
53_563489-bk08ch01.indd 77453_563489-bk08ch01.indd 774 3/19/10 8:17 PM3/19/10 8:17 PM