John Lam 1997 — 2026

Generics stabilizing

RubyCLR now supports multi-type generic types such as Dictionary<T, U>. I also changed the nasty cons method to the infinitely cleaner of method. Here’s some tests to show the progress:

def test_create_two_parameter_generic_type
  dict = Dictionary.of(Int32, Int32).new
  dict.add(1, 1)
  dict.add(2, 2)
  assert_equal 1, dict[1]
  assert_equal 2, dict[2]
end

def test_dictionary_with_string_key
  dict = Dictionary.of(System::String, Int32).new
  dict['John'] = 42
  dict['Ruby'] = 2
  assert_equal 42, dict['John']
  assert_equal 2, dict['Ruby']
end

The one thing that I’m not happy with right now is being forced to fully qualify the System::String type. I might add some code to special-case that type name in the of method and alias to the CLR String type from the Ruby String type.

You might be wondering how I implement the generic types. I generate a Ruby shadow class that has a mangled name. For example, Dictionary.of(Int32,Int32), maps to a Ruby class called Dictionary_generic_Int32_Int32, which is generated the first time of is called. On all subsequent calls, I just look up the Ruby shadow class name. This is also how I handle arrays (you can really think of arrays as a special case of generics).

2 archived reader comments

Justin (2006-03-01)

Very slick! Is there a way to interrogate a generic to get the types it supports out? I can’t think of a reason you might want to do that, but nevertheless that’s what came to mind ;)

John Lam (2006-03-02)

Yes - Type.GetGenericArguments() is your friend. I just wrote some code that used it today.