I had read a ton of articles about that new keyword that is shipping with C# v4, but I couldn't make out the difference between a "dynamic" and "var".
This article made me think about it, but I still can't see any difference.
Is it that you can use "var" only as a local variable, but dynamic as both local and global?
Could you show some code without dynamic keyword and then show the same code with dynamic keyword?
Best Answer
var
is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:and
All that happened was that the compiler figured out that
s
must be a string (from the initializer). In both cases, it knows (in the IL) thats.Length
means the (instance)string.Length
property.dynamic
is a very different beast; it is most similar toobject
, but with dynamic dispatch:Here,
s
is typed as dynamic. It doesn't know aboutstring.Length
, because it doesn't know anything abouts
at compile time. For example, the following would compile (but not run) too:At runtime (only), it would check for the
FlibbleBananaSnowball
property - fail to find it, and explode in a shower of sparks.With
dynamic
, properties / methods / operators / etc are resolved at runtime, based on the actual object. Very handy for talking to COM (which can have runtime-only properties), the DLR, or other dynamic systems, likejavascript
.