The dynamic Keyword Part 1 – Introduction

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:

namespace Mysterious
{
public class TheMysteriousType
{
public string RevealYourSecrets()
{
return "Never!";
}
}
}

Now, I'll create another class library with a method that receives a dynamic variable and executes the RevealYourSecrets method:

namespace Revealer
{
public class Revealer
{
public static void RevealSecrets(dynamic obj)
{
Console.WriteLine("Reveal you secrets, object! {0}", obj.RevealYourSecrets());
}
}
}

And last thing – I'll create a console application that has the above 2 class libraries references. It will contain the following code:

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Mysterious.TheMysteriousType myst = new Mysterious.TheMysteriousType();
Revealer.Revealer.RevealSecrets(myst);
}
}
}

The flow of the application goes like this:

  1. myst variable is created.
  2. Revealer.RevealSecrets gets the myst variable as dynamic.
  3. 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.
  4. 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.

Stay tuned to the next parts!

Happy Holidays!

Shay.

kick it on DotNetKicks.com

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים