First of, let's review a simple example of dynamic (one of the many found out there).
Dynamic can represent any type:
dynamic d1 = 7; dynamic d2 = "a string"; dynamic d3 = System.DateTime.Today; dynamic d4 = System.Diagnostics.Process.GetProcesses();And I can quite easily assign these variables to their statically typed counterparts:
int i = d1; string str = d2; DateTime dt = d3; System.Diagnostics.Process procs = d4;So, I hear you think, that's like var and object. Indeed, like var and object, but with a different flavour. Because with var and object I can also do something like this:
object o1 = 7; object o2 = "a string";
var v1 = 7; var v2 = "a string";Looks the same, right? Yes, but not quite. See, the thing is, object and var are still statically typed, meaning that at compile time their type is checked. The compiler knows o1 is of type integer and o2 is of type string, just as it knows for v1 and v2. The d1, d2, d3 and d4 variables, however, are dynamically typed, meaning their type is not checked at compile time, but at run time.
For a dynamic type I can do this:
int oKButCrashAtRunTime = d2;At compile time I will get no errors whatsoever for this line of code. The compiler says it is valid.
Something I cannot do for object or var:
int notOkAtCompileTime = o2; //compile time error int alsoNotOkAtCompileTime = v2; //compile time errorAt run time however, the line of dynamic code will give me a big fat runtime exception. It's not because something is dynamic you can suddenly assign a string to an integer. So with dynamic types, you need to be extra careful.
These runtime exceptions are part of the reason why people don't like dynamic programming. You only know you've done bad once it crashes (in the user's face). But then why are there tons of programs written in dynamic languages like Ruby? Well, mainly, because Ruby programmers employ a slightly different way of writing code. And if you want the same confidence for your (partly) dynamic .Net code as Ruby programmers have for their (totally) dynamic Ruby code, you will have to learn some of those best practices. Those however, together with a practical .Net example, I will leave for a next post.