John Lam 1997 — 2026

Generics in RubyCLR

I got a crude implementation of generics up and running in RubyCLR today. It does what these tests say it does, and nothing more :)

class GenericsTests < TestCase
  include System::Collections::Generic

  def test_make_generic_type
    c = List.cons(Int32)
    assert_equal 'System::Collections::Generic::List_generic_Int32', c.name
    assert_equal 'System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]', c.clr_type.full_name
  end

  def test_create_generic_type
    list = List.cons(Int32).new
    assert_equal 'List`1', list.clr_type.name
  end

  def test_call_generic_type
    list = List.cons(Int32).new
    list.add(42)
    assert_equal 42, list[0]
  end

  def test_type_conversion_error
    assert_raises TypeError do
      list = List.cons(Int32).new
      list.add('42')
    end
  end
end

As for feedback, I’m not all that happy with the name cons for the method that creates a generic type. Suggestions would be welcome (but they have to be easy to type, since I’m competing with List<Int32> :)

I also ran some crude performance benchmarks for adding 1M integers to each data structure:

  • ArrayList = 1.15s
  • List<Int32> = 1.00s
  • Ruby Array = 0.66s

I just wanted to get some order of magnitude estimates of performance. So far I’m quite happy with the performance of the bridge. 1M method calls / second is nothing to sneeze at.

4 archived reader comments

Dave (2006-03-01)

you could emulate C# syntax with other brackets:

  • List[Int32]
  • List(Int32)
  • List{Int32}

John Lam (2006-03-01)

Hmmm … the first solution doesn’t pan out because of a possible conflict with the syntax for static properties. The second one could work out, but it looks confusing. The third one, using blocks, I haven’t really thought of that before. I’ll have to try that out. Thanks, Dave!

null (2006-03-01)

List.of(Int32).new

John Lam (2006-03-01)

+1 for List.of()