Datasheet

Book VIII
Chapter 1
Programming
Dynamically!
779
Running with the Dynamic Language Runtime
dynamic y = f(array[i]);
if (y > 400.0)
{
Console.WriteLine(string.Format(“{0} TOO
LARGE”, i));
}else{
Console.WriteLine(“{0} : {1}”, i,
array[1]);
}
}
Console.ReadKey();
}
Line for line, the application does the same thing as the Ruby code, albeit
longer. I kept the names the same so it was easier to follow. Because I
had to use for loops to handle the integrators, it made the body of the
program quite a bit beefier. Figure 1-2 shows what the program looks like
when it runs.
Figure 1-2:
The TPK
program
running.
But why use the dynamic type here? Clearly we could have just used double
for this. Use of dynamic just made the program easier to create. Try chang-
ing the array to an array of double, like this:
Double[] array = new Double[11];
Hey, look at that: Now the ReadLine doesn’t work. We’ll just cast it to a
double. Nope, can’t do that; we have to use TryParse. You get the picture.
Static types are hard to code with. Dynamic types are easier to code with.
What’s the other side of this? Well, obviously, if the user enters a string, she
gets a runtime error, and that is bad. If we statically type everything, then we
can trap that error much easier, and handle it right on user input.
53_563489-bk08ch01.indd 77953_563489-bk08ch01.indd 779 3/19/10 8:17 PM3/19/10 8:17 PM