Creating framework objects from class name strings

  • Thread starter Thread starter Oenone
  • Start date Start date
O

Oenone

Hi all,

If I have the name in a string of one of the framework's core classes (such
as "System.Collections.ArrayList"), what's the easiest way for me to create
an instance of the appropriate class?

In VB6 I would have simply used CreateObject, is there an equally simple way
in VB.NET?

Thanks,
 
Oenone said:
If I have the name in a string of one of the framework's core classes
(such as "System.Collections.ArrayList"), what's the easiest way for me to
create an instance of the appropriate class?

'Activator.CreateInstance'.
 
'Activator.CreateInstance'.

Thanks Herfried, got this working fine as follows:

\\\
Dim list As IList
Dim collName As String

collName = "System.Collections.ArrayList"
list =
DirectCast(Activator.CreateInstance(System.Type.GetType(collName)), IList)
///

However, when I set collName to "Microsoft.VisualBasic.Collection" (to get
one of the old VB6-style collections), System.Type.GetType() returns
Nothing. Do you know why?

I'm trying to write some code that knows how to deal with all different
sorts of collections, and it's handling everything except for
Microsoft.VisualBasic.Collection objects just fine. It'd be a shame to have
to put a separate If clause in to specifically create these objects...

Thanks,
 
Oenone said:
\\\
Dim list As IList
Dim collName As String

collName = "System.Collections.ArrayList"
list =
DirectCast(Activator.CreateInstance(System.Type.GetType(collName)), IList)
///

However, when I set collName to "Microsoft.VisualBasic.Collection" (to get
one of the old VB6-style collections), System.Type.GetType() returns
Nothing. Do you know why?

It doesn't know which assembly the type is defined in. You'll have to know
the assembly which contains the type:

\\\
Dim o As Object
For Each a As [Assembly] In AppDomain.CurrentDomain.GetAssemblies()
If a.FullName.StartsWith("Microsoft.VisualBasic,") Then
o = a.CreateInstance("Microsoft.VisualBasic.Collection")
Exit For
End If
Next a
///
 
Just curious as to where one would need to create a Framework object and how
it would be used...Thanks as I'm just learning!
 

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

Similar Threads


Back
Top