views:

4071

answers:

2

Does anyone know how to iterate over a generic list if the type of that list isn't known until runtime?

For example, assume obj1 is passed into a function as an Object:

    Dim t As Type = obj1.GetType
    If t.IsGenericType Then
        Dim typeParameters() As Type = t.GetGenericArguments()
        Dim typeParam As Type = typeParameters(0)
    End If

If obj is passed as a List(Of String) the using the above I can determine that a generic list (t) was passed and that it's of type String (typeParam). I know I am making a big assumption that there is only one generic parameter, but that's fine for this simple example.

What I'd like to know is that, based on the above, how to I do something like this:

    For Each item As typeParam In obj1
        'do something with it here
    Next

Or even something as simple as getting obj1.Count().

Thanks in advance.

+1  A: 

If you know that obj is a Generic List. Then you're in luck.

Generic List implements IList and IEnumerable (both are non-generic). So you could cast to either of those interfaces and then For Each over them.

  • IList has a count property.
  • IList also has a Cast method. If you don't know the type to cast to, use object. This will give you an IEnumerable(Of object) that you can then start using Linq against.
David B
+1  A: 

The method that iterates over your list can specify a generic type:

Public Sub Foo(Of T)(list As List(Of T))
  For Each obj As T In list
     ..do something with obj..
  Next
End Sub

So then you can call:

Dim list As New List(Of String)
Foo(Of String)(list)

This method makes the code look a little hairy, at least in VB.NET.

The same thing can be accomplished if you have the objects that are in the list implement a specific interface. That way you can populate the list with any object type as long as they implement the interface, the iteration method would only work on the common values between the object types.

Todd