Results 1 to 2 of 2

Thread: Create Instance of Class from Class Name

  1. #1
    Bryce Gough's Avatar
    Bryce Gough is offline VB.NET Forum Enthusiast
    .NET Framework
    .NET 4.0
    Join Date
    Mar 2011
    Location
    Perth, Australia
    Posts
    36
    Reputation
    29

    Create Instance of Class from Class Name

    Hey Guys,

    Pretty much what I have is many many classes created, now the user will type a class name and a method and the application will run that method with the supplied arguments. Now I have got it working using:


    Dim method As System.Reflection.MethodInfo
    method = Type.GetType("Code." & Import).GetMethod(MethodName)
    method.Invoke(<New Instance Of Class>, Arguments)


    But I cannot find out how to create an instance of the class from a string.
    '"Code." & Import' is that full class name that I want to create as I have used it in Type.GetType, but that is just getting the method from the class and I need to create an instance of the class to invoke that method.


    Never mind guys, I've fixed it!
    I used:


    Assembly.GetExecutingAssembly().CreateInstance("Code." & Import)


    and it seemed to work fine


    Thanks,
    Bryce Gough
    Last edited by Bryce Gough; 08-18-2012 at 8:44 AM.

  2. #2
    jmcilhinney's Avatar
    jmcilhinney is offline VB.NET Forum Moderator
    .NET Framework
    .NET 4.0
    Join Date
    Aug 2004
    Location
    Sydney, Australia
    Posts
    11,332
    Reputation
    1543
    For future reference, please don't edit your existing post unless you want to change what you posted. If you want to add further information then please add a new post. It just makes things easier to follow. Also, please stick with colours that are actually readable.

    Just as you're getting the appropriate MethodInfo from the Type and invoking it, so you can get the appropriate ConstructorInfo from the type and invoke that. Alternatively, you can also use the Activator.CreateInstance method.

Bookmarks

Posting Permissions

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