locked
instantiate custom type from string RRS feed

  • Question

  • User716593339 posted

    In VB6, you could instantiate and run methods from and object from a string like:

     Public Sub RunMethod(objName As String)

       Dim obj As Object

       Set obj = CreateObject(objName)

       Call obj.SomeMethodName()

       Set obj = Nothing

     End Sub

    How do I do this same thing with a .NET dll?  Say I have the same RunMethod function and am passing in className as String, how would I instantiate the class from the string representation of its name?

    Thanks!

    Wednesday, October 11, 2006 10:06 AM

All replies

  • User1001868398 posted

    C#

    public vouf RunMethod(string objName)

    {

     string obj = objName;

    or

    string obj = new string;

    obj = objName

    }

     

    Hope this helps, now with .NET is easier than every!

    Cheers

    Al

    Wednesday, October 11, 2006 11:43 AM
  • User716593339 posted

    Thanks, but I don't think that will work. ...that just creates a string and sets it equal to the string (objName) that you pass in.  I need to instantiate and actual object from the string that's passed into objName.

     Something that would look like:  Dim obj as Object = CreateObjectFromString(classOrTypeNameString)

    ...where classOrTypeNameString would be, for example "Customers.Customer"

     Thanks!!

    Wednesday, October 11, 2006 11:55 AM
  • User716593339 posted

    Why is it that I can't do this:

    Dim obj as NamespaceA.ClassA

    obj = Ctype(Activator.CreateInstance("NamespaceA", "NamespaceA.ClassA"), ClassA)

    ..you get this error:

    Unable to cast object of type 'System.Runtime.Remoting.ObjectHandle' to type NamespaceA.ClassA.

    But I look at plenty of examples, and they all say to do it this way ...am I doing something wrong?

    Wednesday, October 11, 2006 4:54 PM
  • User2090272125 posted

     

    In c# it works something like this ...

     Type t = Type.GetType(YourString);

    object [] params = new object[]();

    object myObject = Activator.CreateInstance(t, params);

     

    myObject would then be an instance of the type named by its fully qualified name contained in "YourString"

    Saturday, September 6, 2008 7:14 AM