Instansitate a class by String

  • Thread starter Thread starter CJ Taylor
  • Start date Start date
C

CJ Taylor

I think I've seen this somewhere, but I cannot remember how to initialze a
class by a string.

That is, I have a class(Component) that I want to initialize on the fly. It
is derived from a base component I created.

So basically I have.

Public class myDerivedComponent
inherits myBaseComponent

.... stuff ...

End Class

and in another code I want to have

dIm myString as String = "myDerivedComponent"

Dim myD as myBaseComponent

myD.InstanceOf (myString)

Hopefully this makes sense.

-CJ
 
Nevermind found it.

For thsoe that want the answer, its in the Activator class. (System
namespace).

I'll let you know how it goes.

-CJ
 
I was looking into that, but it seemed to much since the method I was
calling was within the Current Executing Assembly.

You would have to work here to understand the weirdness of the situation.
=-)
 
Ok, so Activator isn't working th eway I want to (I could be doing something
wrong)

Here is my current code

Public Function CreateEosBase(ByVal sType As String) As EOSBaseComponent

Dim tType As System.Type

Dim _EOSBase As EOSBaseComponent

Try

tType = System.Type.GetType(sType)

_EOSBase = CType(System.Activator.CreateInstance(tType), EOSBaseComponent)

Return _EOSBase

Catch ex As Exception

Console.WriteLine("Error:" & Me.GetType.ToString() & " " & ex.Message)

End Try



End Function



And type keeps coming back NullReferenceException



Ideas?



CJ
 
Hi CJ,

There's a post in the languages.csharp newsgroup, "opening form by
name", which uses Reflection to invoke the constructor of the class from
which you want an instance. It allows you to pass parameters, if necessary.

Regards,
Fergus
 
Back
Top