C# 4.0 dynamic keyword with IronRuby

In my continued exploration of C# 4.0, I wanted to put together a simple example of using the C# 4.0 "dynamic" keyword in conjunction with IronRuby.  I've been shocked at how difficult it was to find code samples on the internet that actually do this.  With much persistence (and some significant pointing in the right direction from Justin Etheredge) I got my simple example working.  Given that there aren't many great examples of calling IronRuby from C# 4.0 out there, I figured I better post the code.

First off, you need to get the correct version of IronRuby that will work with VS2010 Beta 1.  Next, you want to add the following references to your project (all found in the "bin" folder of the IronRuby download):

  • IronRuby.dll
  • IronRuby.Libraries.dll
  • Microsoft.Scripting.dll

Next, create an IronRuby file called "person.rb" that has the following code:

class Person
    def say_hello
        puts "Hello world!"

Finally, here is the C# code:

ScriptRuntime runtime = IronRuby.Ruby.CreateRuntime();
ScriptScope scope = runtime.ExecuteFile("person.rb");
dynamic person = scope.Engine.Execute("p = Person.new");

Notice the use of the "dynamic" keyword on line 3.  While a full discussion of the dynamic keyword is beyond the scope of this blog post, this keyword is the basis for the dynamic features of C# 4.0 that will be running on top of the Dynamic Language Runtime (DLR) of .NET 4.0.  It will provide a unified way to interact with all things dynamic.  These include:

  • Dynamic languages like IronRuby, IronPython, and JavaScript
  • Simplified .NET Reflection
  • COM Interop
  • DOM objects like HMTL and XML

I'll be speaking at CapArea at the end of this month where the last portion of my talk will be dedicated to C# 4.0 new language features.  Additionally, I'll be devoting an entire talk to C# 4.0 at CMAP in November.

Tweet Post Share Update Email RSS