Use a System.Type in Generics?

C

cmay

Is this something you are not allowed to do?

I basically want to create an instance of a generic class where the
type T is not know at compile time.

e.g.

dim s as System.Type = GetMyType()
dim o as MyObj(Of s)


I have not found a way to do this, so I am guessing it is not possible.
 
H

Herfried K. Wagner [MVP]

cmay said:
I basically want to create an instance of a generic class where the
type T is not know at compile time.

e.g.

dim s as System.Type = GetMyType()
dim o as MyObj(Of s)

\\\
Dim GenericType As Type = GetType(List(Of ))
Dim ParameterTypes() As Type = {GetType(Integer)}
Dim o As Object = _
Activator.CreateInstance( _
GenericType.MakeGenericType(ParameterTypes) _
)
///
 
C

cmay

Thanks HKW!

\\\
Dim GenericType As Type = GetType(List(Of ))
Dim ParameterTypes() As Type = {GetType(Integer)}
Dim o As Object = _
Activator.CreateInstance( _
GenericType.MakeGenericType(ParameterTypes) _
)
///
 
C

Cor Ligthert [MVP]

Herfried,

I am curious how I can use this Generic List of a typed class, while I don't
know the members of the class?

Can you give me an example?

Cor
 
H

Herfried K. Wagner [MVP]

Cor Ligthert said:
I am curious how I can use this Generic List of a typed class, while I
don't know the members of the class?

The problem is that you can only do that using reflection because 'List(Of
X)' is not a 'List(Of )'. Thus I do not think that the solution I posted
makes much sense because generics are mainly a compile-time feature and the
compile-time advantages are lost when using reflection.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top