Dynamic Language Support in the .NET 4.0 Framework

Introduction

Welcome to this installment of the .NET Nuts & Bolts column! The focus of this article will be on the dynamic language support that will be released as a part of the upcoming 4.0 version of the .NET Framework. In order to run the examples contained within this article you'll need to use an early preview such as a beta or CTP of the .NET Framework 4.0 release.

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

Dynamic Language Runtime (DLR)

Dynamic languages are those that have a loose coupling between applications and data services. They involved implicit typing, meta programming, and do not involve compilation. The popularity of dynamic languages such as Python, Ruby, and JavaScript can be seen all across the Internet. To date Microsoft .NET has been about static languages.

The argument for and against dynamic languages and static languages has been around since programming languages were first created. Each paradigm has its strengths and weaknesses. The Common Language Runtime (CLR) is a common platform introduced in Microsoft .NET 1.0 for statically typed objects. Since the static paradigm was the only paradigm supported, those seeking support for dynamic languages were forced to turn elsewhere.

The Dynamic Language Runtime (DLR) introduces support for dynamic 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, and call side caching to avoid resolving to the same location more than once. The DLR interfaces with other platform types via binders. There are binders that map dynamic objects to statically typed .NET objects, a JavaScript binder that allows binding directly to JavaScript in Silverlight applications, COM objects, and Python and Ruby. It provides a single programming experience for talking to all of these environments that are not statically typed.


Figure 1 - Dynamic Language Runtime

Dynamic Language Support in the .NET 4.0 Framework

Dynamically Typed Objects

It is not uncommon to have to interact with objects differently depending upon the source technology. The following example code depicts the differences in calling a simple calculator that is based on managed code, COM, or JavaScript. You will see the syntax is very different to accomplish the same thing. The examples each assume we have defined 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 will introduce a new dynamic type. The name can be concerning to folks, but rest assured it is actually a static type despite the assigned name of dynamic. Rather than having member selection and type selection at compile time it is deferred until run-time. It behaves similarly to normal static types in other ways. The result is that the managed code, COM Interop, and JavaScript examples above can all be replaced with 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 declarations involving 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 member selection at compile time compared to dynamic where it is deferred 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 to use multiple languages in our project. The following Python code was defined in a Calculator.py source code file. It defines 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 the Python 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 DLR brings support for dynamic languages to .NET and creates a scenario where you can leverage the best of static and dynamic languages in your applications. You learned how the keyword dynamic represents statically typed dynamic objects. At run-time actual type(s) are substituted for dynamic and member selection is deferred until run-time. Hopefully the examples gave you an idea of the simplicity and power of the object binders.

Future Columns

The topic of the next column is yet to be determined. It will most certainly be something focused towards the next release of the .NET Framework. If you have something in particular that you would like to see explained here you could reach me at mark .strawmyer@crowehorwath.com.

About the Author

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader in Indianapolis, Indiana. He specializes in architecture, design and development of Microsoft-based solutions. Mark was once again honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mark .strawmyer@crowehorwath.com.



About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: August 13, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT If you are developing applications, you'll want to join us to learn how applications are changing as a result of gesture recognition. This technology will change how you and your users interact - not simply with your devices, but with the world around you. Your devices will be able to see and hear what your users are doing. Are your applications ready for this? Join us to learn about Intel® RealSense™ Technology, including never been …

  • Savvy enterprises are discovering that the cloud holds the power to transform IT processes and support business objectives. IT departments can use the cloud to redefine the continuum of development and operations—a process that is becoming known as DevOps. Download the Executive Brief DevOps: Why IT Operations Managers Should Care About the Cloud—prepared by Frost & Sullivan and sponsored by IBM—to learn how IBM SmartCloud Application services provide a robust platform that streamlines …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds