When I heard about the new dynamic keyword in C# 4.0 I was confused.Why there is a new keyword where var works for me if I don’t know the data type. After digging into the concept I could understand the need for dynamic keyword.
var is type safe ie when we click on the dot(.) it will display the public members of the type which the var is currently holding.But dynamic on the other hand will not be able to display the list.There will be no compilation error on the dynamic keyword even if we use some junk characters as its member methods or properties.Its just like the old style programming where there is no type safety.At run time the method or property may or may not be there.
Internally how dynamic is handled is just a reflection code.It checks for the member through reflection and it invokes the member if exists.Else throws exception.If you want to see the reflected code of dynamic keyword just use the reflector.
Object v/s dynamic
Object is just the base class.in other words all the other classes inherits from this and its type safe.That means you can’t compile code ,if the object variable is trying to invoke members other than its defined members.
|Supports as method argument type||Yes||No||Yes|
|As source in for each iteration||Not supported||Supported||Supported|
|Application areas||To hold objects as base class.||Linq queries,||Com interop|
|Need type casting on assignment||Yes||No||No|
|Compilation examples ||Object o = new Button(); |
o.Width doesn’t compile
|var o = new Button(); |
o.Width will compile
|dynamic o = new Button(); |
o.Width and even o.xyz() will compile where xyz is not a member
I know this is a small list.There may be more scenarios with memory usage and speed of execution.If time permits I would be adding more.
I was able to see a real good application of dynamic when I worked on browser interaction from Silverlight.My Silverlight blog will get that sample soon.