instantiate object using 'new' keyword


I'm having a mental block - I may have once known the answer to this but for the life of me can't recall it!

I want to create a new object at run time.  What I don't want to do is this:

strAString = "datObject1" ' Defined elsewhere
Select Case strAString

   Case "datObject1"
      Dim anObject As datObjectTemplate = new datObject1

   Case "datObject2"
      Dim anObject As datObjectTemplate = new datObject2

End Select

As there are lots of objects and they all inherit from datObjectTemplate.  What I do want to do is something like this:

strAString = "datObject1" ' Defined elsewhere
Dim anObject As datObjectTemplate = new ???

So my question is, what can I replace ??? with to be able to determine the type of object that is created from the contents of the strAString variable and without having to test the contents of the strAString variable and write a seperate Dim line for each possibility?!!  I'm open to other suggestions - I just want to avoid the select case avenue!

Thanks a lot for looking
Who is Participating?
Ignacio Soler GarciaConnect With a Mentor Solution Architech & Technical LeadCommented:
This is done with the Class Activator in this way:

Dim s As String = "<FullQualifiedNameOfTheClass>"
Dim a As Object

a = System.Activator.CreateInstance(System.Type.GetType(s))

and now the a have the instance that you want.

Askme for more if you need.

Yes, you can do that using reflection, give me a second and I'll dig up some example
sbhodgeAuthor Commented:
Hi SoMoS

Thanks a lot, thats solved the problem perfectly - you certainly are worthy of the title 'expert'.

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

sbhodgeAuthor Commented:
Ronald, thanks for your interest and time too.

Ignacio Soler GarciaSolution Architech & Technical LeadCommented:
Not really, just a common OOP developer with 12 hours a day of wrk and with good skills with google and vstudio help ;)
sbhodgeAuthor Commented:
Ahh, you're too modest!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.