IronShay

19 בדצמבר 2008

Firstly, in order to use the dynamic keyword, you'll have to download the VS2010 VPC image and work there. There is no way currently, to download and install Visual Studio 2010 on your local computer.

Now we're ready to explore the future!

So what is the dynamic keyword?

The dynamic keyword is a new type of variable that will be added to the syntax of C# 4.0. Behind the scenes, the dynamic keyword is declared as an object with an attribute that indicates that this is a "special" object that should be treated dynamically.

The way you declare it is just like any other variable type:

dynamic myDynamicVariable = something;

What is it good for?

This dynamic mechanism is a wonderful thing for a bunch of different things that now we have trouble with. Things like – reflection in different environments, calling dynamic languages, dynamic fluent interfaces and more. All of these will become tremendously easier, using the dynamic keyword.

Example – Reflection using dynamic

Let's say I have a type that I define on one class library, I'll call it TheMysteriousType. This is its code:

Inside Revealer.RevealSecrets: obj.RevelarYourSecrets() will generate a dynamic invocation of the RevealYourSecrets method. Behind the curtains, this will end up running the traditional reflection code for us.

The application ends up writing to the screen: "Reveal your secrets, object! Never!".

This is a sample reflection scenario – the Revealer class does not know the object it receives. In order to invoke the RevealYourSecrets method prior to C# 4, we had to use some complicated reflection code. From C# 4, we'll have the dynamic keyword on our side that will do that for us.

This is great because it saves us time and make our code more readable, eventually making it easier to maintain.