Results 1 to 3 of 3

Thread: Create an instance of an object from a string

  1. #1

    Thread Starter
    Registered User
    Join Date
    Nov 2002
    Location
    Växjö, Sweden
    Posts
    314

    Create an instance of an object from a string

    Hi there all!

    I have a question:

    Is it possible to create an instance of an object if you have the name of the object in a string value?

    In VB6 you could use the CreateObject Method like this for example:

    Set xlApp = CreateObject("Excel.Apllication")

    or something similiar I think. I have seen that the CreateObject function is still there, but didnt get lucky trying it out. CreateObject("Form1") for example, did not do the job.

    I have a way around this problem, but this would sure save me a couple of pages of code.

    Thanks!
    /Leyan

  2. #2
    PowerPoster Lethal's Avatar
    Join Date
    Oct 2000
    Location
    Ohio
    Posts
    2,496
    You should be able to using Reflection. Check out the System.Reflection namespace. I'm not on my home computer, so I can't dig up an example right now.

  3. #3

    Thread Starter
    Registered User
    Join Date
    Nov 2002
    Location
    Växjö, Sweden
    Posts
    314
    It sure worked with reflection.....

    Code:
    Dim ty As Type = Type.GetType("Test.Form2")
    Dim o As Object = Activator.CreateInstance(ty)
    Dim mi As MethodInfo = ty.GetMethod("Show")
    Dim params(mi.GetParameters.Length - 1) As Object
    mi.Invoke(o, params)
    You're a hat full of flowers.

    Thanks alot

    /Leyan

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width