Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining the type of a List in vb.net at runtime

Tags:

vb.net

I'm creating a class at run time using typebuilder and after I create this class I want to define its type for a list like

dim fooList as new List(of DynamicClassName)

Since this doesn't exist at compile time of course it throws an error. When I generate this type I return the type so I can't do something like

dim newType = createNewType(foobar)
dim fooList as new List(of getType(newType))

How do I assign the type of a List at runtime?

like image 980
Luminous Avatar asked Oct 17 '25 11:10

Luminous


1 Answers

You can create a List(Of T), but AFAIK you won't be able to cast it to a typed object. I've used the String type in the following example.

Dim list As Object = Activator.CreateInstance(GetType(List(Of )).MakeGenericType(New Type() {GetType(String)}))

Debug.WriteLine((TypeOf list Is List(Of String)).ToString())

Output

True

So in your case it would look like this:

Dim newType = createNewType(foobar)

'Creates a List(Of foobar):
Dim list As IList = Ctype(Activator.CreateInstance(GetType(List(Of )).MakeGenericType(New Type() {newType})), IList)

'Creates a BindingList(Of foobar):
Dim bindingList As IBindingList = Ctype(Activator.CreateInstance(GetType(BindingList(Of )).MakeGenericType(New Type() {newType})), IBindingList)
like image 181
Bjørn-Roger Kringsjå Avatar answered Oct 20 '25 08:10

Bjørn-Roger Kringsjå



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!