About .NET 4.0 Series - I'll be covering various aspects of .NET 4.0 and related technologies in these posts
C# 4.0 introduced the
dynamickeyword, to support dynamic typing. If you assign an object to a dynamic type variable (like
dynamic myvar=new MyObj()), all method calls, property invocations and operator invocations on myvar will be delayed till the run time, and the compiler won't perform any type checks for myvar at compile time.
So, if you do something like myvar.SomethingInvalid(); it is valid at compile time, but invalid at runtime if the object you assigned to myvar doesn't have a SomethingInvalid() method.
The System.Dynamic namespace has various classes for supporting dynamic programming, mainly the DynamicObject class from which you can derive your own classes to do run time dispatching yourself.
A couple of points to note.
- A dynamic call will be slower for the first time, and your calls will be jited and cached if possible for subsequent calls. As a first step, the DLR checks the cache to see if the given action has already been bound wrt to the arguments. If not, the DLR checks to see if the receiver is an IDynamicObject, and if so, asks the receiver to bind the action. If the receiver is not an IDO, then DLR calls into the language binder (i.e, the C# runtime binder), and cache this.
- C#'s underlying type system has not changed in 4.0. As long as you are not using dynamic keyword, you are still statically typed (i.e, the types are known for the compiler at compile time).
- Error handling when you use dynamic features is a bit difficult and can't be very specific, as you don't know much about the foreign objects to which you dispatch the calls.
Recently, I published this article in Codeproject;
- Creating a dynamic wrapper around the file system so that we can access Files and Directories as properties/members of a dynamic object
- A way to attach custom Methods and operators to our dynamic wrapper class and dispatch them to a plug in sub system.