The new keyword “dynamic” added to C# (.Net 4.0) allows you to interoperate with any dynamic language such as IronPython or IronRuby.
This new feature bypasses any static type checking at compile time, assuming that any operation is allowed. But, if it is not allowed, an error will be showed at run time.
For example, the following Customer “IronPython Class” is invoked from the C# code as a dynamic object:
IronPython code (Sample.py)
# Function (method) that creates a new Customer
def CreateCustomer(firstName, lastName):
return Customer(firstName, lastName)
# Customer object
class Customer(object):
# Initialization (constructor)
def __init__(self, firstName, lastName):
self._firstName = firstName
self._lastName = lastName
# Function (method) that print the customer
def printNames(self):
print self._firstName + ' ' + self._lastName
C# code (Program.cs)
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
class Program
{
static void Main(string[] args)
{
ScriptRuntime py = Python.CreateRuntime();
dynamic sample = py.UseFile("Sample.py");
dynamic customer = sample.CreateCustomer("Paul", "Smith");
customer.printNames();
}
}
You can download the source code here.