Question Generics and System.Type

jchunn

New member
Joined
Jul 5, 2008
Messages
1
Programming Experience
10+
In the code below, I am trying to create a collection of "SomeClass" objects, each one being created based on the generic type chosen by the caller of "CreateSomeList", like this:
VB.NET:
Dim c as Collection = CreateSomeList(GetType(Integer), GetType(Single), GetType(Double), GetType(Date))
. The problem is that the line "Dim sc as SomeClass(Of t)" fails to compile, saying "Type 't' is not defined.". Here is the complete code to reproduce:

VB.NET:
    Public Function CreateSomeList(ByVal ParamArray Types() As System.Type) As Collection

        Dim somelist As New Collection

        For Each t As System.Type In Types
            Dim sc As SomeClass(Of t) ' this is the line that fails to compile
            somelist.Add(sc)
        Next

        Return somelist
    End Function

    Public Class SomeClass(Of T)
        Private mValue As T
        Public Property Value() As T
            Get
                Return mValue
            End Get
            Set(ByVal value As T)
                mValue = value
            End Set
        End Property
    End Class

How can I make this work?:confused:
 
Use Type.MakeGenericType to compose the generic type and Activator.CreateInstance, example:
VB.NET:
Dim t As Type = GetType(SomeClass(Of ))
t = t.MakeGenericType(GetType(Integer))
Dim o As Object = Activator.CreateInstance(t)
I'd choose ArrayList or List(Of Object) collections over the VB6 Collection.
 
Back
Top