http://www.developer.com/

Back to article

Dynamic Language Support in the .NET 4.0 Framework


December 11, 2009

Introduction

Welcome to this installment of the .NET Nuts & Boltscolumn! The focus of this article will be on the dynamiclanguage support that will be released as a part of theupcoming 4.0 version of the .NET Framework. In order to runthe examples contained within this article you'll need touse an early preview such as a beta or CTP of the .NETFramework 4.0 release.

Note: In order to run the examples contained withinthis article you'll need to use an early preview such as abeta or CTP of the .NET Framework 4.0 release.

Dynamic Language Runtime (DLR)

Dynamic languages are those that have a loose couplingbetween applications and data services. They involvedimplicit typing, meta programming, and do not involvecompilation. The popularity of dynamic languages such asPython, Ruby, and JavaScript can be seen all across theInternet. To date Microsoft .NET has been about staticlanguages.

The argument for and against dynamic languages and staticlanguages has been around since programming languages werefirst created. Each paradigm has its strengths andweaknesses. The Common Language Runtime (CLR) is a commonplatform introduced in Microsoft .NET 1.0 for staticallytyped objects. Since the static paradigm was the onlyparadigm supported, those seeking support for dynamiclanguages were forced to turn elsewhere.

The Dynamic Language Runtime (DLR) introduces support fordynamic languages on .NET. This creates the possibility of a"best of" scenario where you can use from both paradigms.The core infrastructure of the DLR includes expression trees(such as LINQ), dynamic dispatch to different binders, andcall side caching to avoid resolving to the same locationmore than once. The DLR interfaces with other platform typesvia binders. There are binders that map dynamic objects tostatically typed .NET objects, a JavaScript binder thatallows binding directly to JavaScript in Silverlightapplications, COM objects, and Python and Ruby. It providesa single programming experience for talking to all of theseenvironments that are not statically typed.


Chart showing Dynamic Language Runtime Flow
Click here for larger image

Figure 1 - Dynamic Language Runtime

Dynamically Typed Objects

It is not uncommon to have to interact with objectsdifferently depending upon the source technology. Thefollowing example code depicts the differences in calling asimple calculator that is based on managed code, COM, orJavaScript. You will see the syntax is very different toaccomplish the same thing. The examples each assume we havedefined a calculator object.

  // Managed code  Calculator calc = GetCalculator();  int sum = calc.Add(10, 20);    // COM Interop  object calc = GetCalculator();  Type calcType = calc.GetType();  object res = calcType.InvokeMember("Add",      BindingFlags.InvokeMethod, null, new object[] { 10, 20 });  int sum = Convert.ToInt32(res);    // JavaScript  ScriptObject calc = GetCalculator();  object res = calc.Invoke("Add", 10, 20);  int sum = Convert.ToInt32(res);

The next release of both C# and Visual Basic willintroduce a new dynamic type. The name can be concerning tofolks, but rest assured it is actually a static type despitethe assigned name of dynamic. Rather than having memberselection and type selection at compile time it is deferreduntil run-time. It behaves similarly to normal static typesin other ways. The result is that the managed code, COMInterop, and JavaScript examples above can all be replacedwith the following example code:

  // Statically typed to be dynamic  dynamic calc = GetCalculator();    // Dynamic method invocation and dynamic conversion of type  int sum = calc.Add(10, 20);

When operands are dynamic:

  • At run-time, actual type(s) are substituted for dynamic
  • Member selection is deferred until run-time
  • Static result type of operation is dynamic

The following sample code demonstrates declarationsinvolving dynamic types.

  // compile-time type dynamic, run-time type System.Int32  dynamic x = 1;    // compile-time type dynamic, run-time type string  dynamic y = "Hello";    // compile-time type dynamic, run-time type List<int>  dynamic z = new List<int> {1, 2, 3};

The following sample code demonstrates normal memberselection at compile time compared to dynamic where it isdeferred until run-time.

  // Method chosen at compile time  double x = 1.75;  double y = Math.Abs(x);     // Method double Abs(double x) chosen at run-time  dynamic x = 1.75;  dynamic y = Math.Abs(x);     // Method int Abs(int x) chosen at run-time  dynamic x = 2;  dynamic y = Math.Abs(x);

Python Object Binder Example

Let's take a look at how dynamic types even allow us touse multiple languages in our project. The following Pythoncode was defined in a Calculator.py source code file. Itdefines a simple calculator object.

  def GetCalculator():    return Calculator()       class Calculator(object):    def Add(self, x, y):       return x + y

The following C# code will create an instance of thePython run-time and use the calculator.

  // Load the Python run-time  dynamic python = Python.CreateRuntime().UseFile("Calculator.py");    // Get an instance of the calculator  dynamic calc = python.GetCalculator();    // Loop and demonstrate use  for (int i = 0; i &lt; 10; i++)   {              int sum = calc.Add(100, i);              Console.WriteLine(sum);  }

Summary

You have learned about how the introduction of the DLRbrings support for dynamic languages to .NET and creates ascenario where you can leverage the best of static anddynamic languages in your applications. You learned how thekeyword dynamic represents statically typed dynamic objects.At run-time actual type(s) are substituted for dynamic andmember selection is deferred until run-time. Hopefully theexamples gave you an idea of the simplicity and power of theobject binders.

Future Columns

The topic of the next column is yet to be determined. Itwill most certainly be something focused towards the nextrelease of the .NET Framework. If you have something inparticular that you would like to see explained here youcould reach me at mark.strawmyer@crowehorwath.com.

About the Author

Mark Strawmyer is a Senior Architect of .NET applicationsfor large and mid-size organizations. Mark is a technologyleader in Indianapolis, Indiana. He specializes inarchitecture, design and development of Microsoft-basedsolutions. Mark was once again honored to be named aMicrosoft MVP for application development with C#. You canreach Mark at mark.strawmyer@crowehorwath.com.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date