November 28, 2014
Hot Topics:

Dynamic Language Support in the .NET 4.0 Framework

  • December 11, 2009
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

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.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel