Ironing code, geek t-shirts and even presentations!


IronRuby Tip: Using Generic CLR Methods from IronRuby

A while ago I wrote a post about using Generic CLR classes from IronRuby. This time I’ll share with you its less intuitive friend – using generic CLR methods from IronRuby.

As a result of Ruby being a duck-typed language which works with types implicitly, generics is not really needed. The whole language is generic… This is why using generic CLR types might become a bit odd for the language. Nonetheless, this fact will not stop us. The price to pay in order to enjoy Ruby in the .Net framework is worth it! :)

Anyway, assuming we have the following C# class defined in file sample.dll:

namespace ClassLibrary1
    public class Class1
        public string Test<T>(T param)
                return param.ToString();

In order to use it with a specific type, you need to do two things – get the generic method object (by using the method method) and provide it with the type via the special of method. For example, the next code invokes Test with a string and pass it “Shay Friedman”:

require "sample.dll"

sample =
sample.method(:test).of(String).call("Shay Friedman") # returns "Shay Friedman"

And that’s all there is to know.

All the best,

Pingbacks and trackbacks (1)+

Add comment