2

An example:

Dim myFoo as FooClass()
Dim fooType = myFoo.GetType()

'This is how it's normally done...
Dim myList as List(Of FooClass) = nothing

'I need to basically do something like this
Dim myOtherList as List(Of fooType) = nothing

Basically, I'm trying to dynamically create a generic object based on the Type. Is there a way to do this?

Thanks, Sam.

Sam
  • 1,325
  • 1
  • 13
  • 26
  • what are you trying to do? `T` needs to be a defined type for the compiler, not something To Be Determined later. (and `= Nothing` is redundant) – Ňɏssa Pøngjǣrdenlarp Oct 23 '14 at 18:39
  • What I'm actually trying to do is to automatically map entities in the entity framework. All the entities implement a specific interface. So I get all the types from the assembly and find the ones with that interface. I want to then automatically map them to a corresponding table name. – Sam Oct 23 '14 at 18:47
  • 1
    As Plutonix said, the type of a variable must be known at compile time, so the best you could do is `Dim myOtherList As IList` (non-generic) and create and instance of `List(Of fooType)` at runtime using reflection (should probably add - AFAIK - since sometimes I don't know much!). – Mark Oct 23 '14 at 18:58
  • 1
    You don't really need a generic for this. You could make the list a List (Of Object) but the best solution is probably to make it a List (Of ISpecificInterface) since you said that you are looking for types that implement a specific interface. – Grax32 Oct 23 '14 at 19:44
  • Yeah, I tried the interface part... It doesn't work because the Entity Framework can't infer the class from that. It needs the actual class to map the entity to the database. – Sam Oct 23 '14 at 23:53

1 Answers1

0

A few days ago I bumped into almost the same problem.

It can be solved using reflection.

See this:

Dim variable as datatype stored in db field

Community
  • 1
  • 1
ilans
  • 2,537
  • 1
  • 28
  • 29
  • That's not the same thing though... I don't need an actual instance of the object... I need a "Class" type for the generic constructor. – Sam Oct 23 '14 at 18:45
  • Why don't you initiate an object of type `Object` ? or create inheritance of some class? sounds like you could have solved this that way. Try to think out of the box, and not be locked on the concept you've stated here. – ilans Oct 23 '14 at 18:55
  • @Verdolino funny guy. I didn't ask the question! can't accept the answer... but if it were me - I would have accepted it without reading :))) – ilans Oct 23 '14 at 19:34
  • 1
    @Verdolino - We are all human beings.. Though some of our middle east neighbors and some few extremists of our own people forgot that. :) – ilans Oct 23 '14 at 19:37