Search code examples
c#.netextension-methodsironruby

IronRuby calling C# Extension Methods - Error - Compatibility in .NET 3.5


I have written an Extension Method off of DataGridView called HideColumns.

public static class Extensions
{
    public static void HideColumns(this DataGridView dataGridView, params string[] columnNames)
    {
        foreach (string str in columnNames)
        {
            if (dataGridView.Columns[str] != null)
            {
                dataGridView.Columns[str].Visible = false;
            }
        }
    }

}

I pass my grid into an IronRuby script as a variable called main_grid

When my script calls main_grid.HideColumns("FirstName","LastName") the script blows up with Error in Script undefined method 'HideColumns' for System.Windows.Forms.DataGridView:System::Windows::Forms::DataGridView

The extension methods seem to work okay from C#. What gives?


Solution

  • FWIW, IronRuby 1.1 (needs .net 4) provides the using_clr_extensions method -- as noted in the release notes this activates all extension methods defined on classes defined in a given namespace, regardless of the assembly they are defined in; assemblies loaded in the future that define extension methods in the activated namespace will automatically appear on the correct types, like this:

    load_assembly "System.Core"
    using_clr_extensions System::Linq
    
    # ...
    
    products.
      where(lambda { |p| p.units_in_stock == 0 }).
      each { |x| puts x.product_name }
    

    The release notes also point at a whole set of examples at http://github.com/ironruby/ironruby/blob/master/Languages/Ruby/Samples/Linq/101samples.rb