Extending C# Classes in IronRuby

Ruby provides several ways to extend classes — subclassing, mixins, and monkey-patching. How can we send IronRuby a C# class and extend it?

I experimented with several approaches. Here’s a run-down of what worked, and what didn’t.

But first, the basics: I created a very simple C# class to experiment with:


namespace IronRubyTest {
class Cat {
public string Name { get; set; }
public Cat(string name) { this.Name = name; }
public string Talk() {
return string.format("{0} meows", this.Name);
}
}
}

With that in mind, on to the (non-animal!) experimentation!

Monkey-Patching

Monkey-patching, in this context, means adding methods to a class when you don’t have the source. A simple example:


class String
def say_hi
return "HI!"
end
end

puts "some string".say_hi # prints "HI!"

Monkey-patching doesn’t work, mysteriously; even if you use load_assembly to make the CLR types equivalent (as mentioned in a previous post), the new methods don’t appear:


load_assembly 'IronRubyTest'
class IronRubyTest::Cat
def Meow
return "MEOW!!!"
end
end

return IronRubyTest::Cat.new('Snowball')

This code, paradoxially, returns the old type of IronRubyTest.Cat; even if I type it to dynamic, I get an error that IronRubyTest.Cat does not contain a definition for 'Meow'. Disappointing.

Even more disappointing, I couldn’t override the method in Ruby. It just ran the C# version.

Subclassing

This works:


class Cat < IronRubyTest::Cat def Meow return "MEOW from Ruby!" end end return Cat.new('Sapphire') end

Not only did I get back a cat which responds to Talk and has a public Name field, but it responds to cat.Meow with MEOW from Ruby!

The only caveat is that the type returned is Cat$1, which is surprising (or maybe not so surprising considering it's a subclass).

But it works. In fact, I'm sure I can define abstract classes and interfaces in C# and implement them in custom subclasses in Ruby.

But that's an experiment for another day.

Conclusion

Extending C# classes in Ruby is not that easy, but it's possible. One approach worked, one didn't. Did you try a third approach? How did it pan out for you?

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *