views:

46

answers:

2

I have a function that looks similar to the following. I'd like to modify it so I can pass in multiple types to filter on instead of just one. I don't suppose there's a params/paramarray option for type parameters, is there?

Public Shared Function Filter(Of T)()
    Dim results As New List(Of T)
    For Each item In GlobalCollection.All()
     If GetType(T).IsAssignableFrom(item.GetType()) Then
      results.Add(instance)
     End If
    Next
    Return results.ToArray()
End Function

I'd like to be able to call it like:

Filter(Of Car)

and also like:

Filter(Of Car, Truck, Boat)
+3  A: 

No, the number of type parameters is fixed at compile time (for generic types and methods). However, you can overload by the number of type parameters - so you can come up with N different versions of your methods, with different numbers of type arguments.

(That's a bit like Action, Action(Of T), Action(Of T1, T2) etc.)

Jon Skeet
I'd like it so I can pass in any number of types though.
adam0101
That's just not supported, I'm afraid. I can't immediately see how your method would be extended to more than one type anyway...
Jon Skeet
+1  A: 

You could make the function looks more like this:

Public Shared Function Filter()(ByVal FilterTypes As IEnumerable(Of Type)) As IList(Of Object)

But then you'd have to return a collection of Objects.

A much better option is to define an inheritance structure of some kind (could be an interface) for your types. So your 'Car', 'Truck', and 'Boat' types would all implement or inherit from a base 'Vehicle' type.

Joel Coehoorn