[Ironruby-core] Calling .Net generic method with Ruby object

Alexander Ranger lists at ruby-forum.com
Thu Jul 26 06:16:31 UTC 2012


Re: [Ironruby-core] Calling .Net generic method with Ruby object
Orion Edwards
Wed, 18 Jul 2012 13:59:01 -0700

The .NET method can't accept normal IronRuby objects, because of the 
new()
constraint.

IronRuby objects behind the scenes are all instances of A .NET class
called RubyObject - you can see it's code here:
https://github.com/IronLanguages/main/blob/master/Languages/Ruby/Ruby/Builtins/RubyObject.cs

RubyObject has 2 constructors, both of which require parameters... Your
new() constraint says "I can only accept methods with public 
zero-argument
constructors"... RubyObject doesn't satisfy this (and neither do many 
many
other .NET classes), so it simply doesn't work.

If you remove the new() constraint, you can pass Ruby objects to the 
Store
method.


There is another way to do this also. If you create a blank .NET class
with a default constructor, and have your ruby classes derive from it,
then IronRuby will create instances of those classes instead of
RubyObject.
You can then call the Store method and use the .NET class as the T.
Remember, C# can't see any of the ruby methods, but it will also allow 
you
to "store" the object.

Here's my example code:

C#:

public static class Demo
{
    public static void Store<T>(T obj) where T : class, new()
    {
        Console.WriteLine("Storing {0}", obj);
    }
}

public class SimpleObject
{
    public SimpleObject() { }
}

IronRuby:

class X < SimpleObject; end

x_instance = X.new
Demo.method(:Store).of(SimpleObject).call x_instance

# This prints "Storing IronRuby.Classes.SimpleObject$1"

If it's ok, can I ask what you're trying to do here? Normal .NET code
can't really interact with ruby objects unless it's built to use the C# 
4
dynamic keyword, or has special knowledge of the Dynamic Language 
Runtime
API's... If you're just putting ruby objects in a list so that ruby code
can retrieve them later that will be fine, but if you're trying to do
other things, you may run into problems...


______________________________________________________

Orion Edwards | Technical Leader
PHONE +64 7 838 9800 | FAX +64 7 838 9801 |
EMAIL orion.edwa... at gallagher.co | WEB www.gallagher.co

-- 
Posted via http://www.ruby-forum.com/.


More information about the Ironruby-core mailing list