Creating a Generic List of a specified type

11,422

Solution 1

If callers know the type, you can make the method itself generic:

Public Shared Sub create(Of t)() 
    Dim myList As New Generic.List(Of t)
End Sub

If callers do not know the type, you'll have to resort to reflection - see the accepted answer to this question for more information.

Solution 2

I have a function to do exactly that:

Public Shared Function CreateList(Of T)(ByVal ParamArray items() As T) As List(Of T)
    Return New List(Of T)(items)
End Function

For instance, I can create a list of integers by doing this:

dim L as list(of Integer) = CreateList(1,2,3,4,5)

Or create a list of, say, textboxes:

dim L as list(of TextBox) = CreateList(txtPhone1, txtPhone2, txtPhone3)

Or in general, any type.

Share:
11,422
Admin
Author by

Admin

Updated on June 06, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to create a generic list - but I want to specify the type at runtime - is there a way I can do this? using reflection perhaps?

    Something like this...

    Public Shared Sub create(ByVal t As Type) 
    
      Dim myList As New Generic.List(Of t)
    
    End Sub
    

    Thanks in advance

    James