Creating a class instance using a string name

I need to create a class using the name of the class as a string variable. [For background: What I want to do is to run a batch process from an XML file. The XML file contains the name of the class, the parameters for the constructor, and then the method(s) to call with its parameter values, in nested XML blocks]. I have a handle on the XML stuff and I know how to call the method, and get its parameter information using Reflection.
But I cant find how to create a class using a name in string format. The solution should also show how I can find the parameter details for the class constructor, so I can typecast the XML element values (string) to the correct type before calling the constructor. I am looking for a Visual Basic code snippet that will show me how to do this.
Fritz41Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

omegaomegaDeveloperCommented:
Hello, Fritz41,

See if the attached snippet gives you any ideas.  I think that there must be a better (more general) way to define the parameter types than the stupid Select Case that I have here, but I am too tired to think of it tonight.  Please post back with the better way of doing it, if you can see what it is.

Cheers,
Randy
Public Class Class1
    ' This is just a dummy class for demonstration purposes.
    ' It has a constructor with parameters.
    Dim _Parameter1 As String
    Dim _Parameter2 As Integer
 
    Public Sub New(ByVal Parameter1 As String, ByVal Parameter2 As Integer)
        _Parameter1 = Parameter1
        _Parameter2 = Parameter2
    End Sub
 
    Public ReadOnly Property ParameterOne() As String
        Get
            Return _Parameter1
        End Get
    End Property
 
    Public ReadOnly Property ParameterTwo() As Integer
        Get
            Return _Parameter2
        End Get
    End Property
 
End Class
 
Option Strict Off
Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 
        Dim strClassName As String = GetType(Class1).FullName   ' This would come from XML file.
        Dim strFirstParam As String = "First Parameter"         ' So would this
        Dim strSecondParam As String = "1234"                   ' and this.
 
        ' Prepare the information required.
        Dim typToCreate As Type = Type.GetType(strClassName)
        Dim ConstrInfo() As Reflection.ConstructorInfo = typToCreate.GetConstructors
        Dim ParamInfo() As Reflection.ParameterInfo = ConstrInfo(0).GetParameters
        Dim objaParam(ParamInfo.Length - 1) As Object    ' Watch out for case of no paramters (not handled here).
        For intParam As Integer = 0 To ParamInfo.Length - 1
            Dim Param As Reflection.ParameterInfo = ParamInfo(intParam)
            Dim typParam As Type = Param.ParameterType
            Select Case Param.ParameterType.Name
                Case "String"
                    objaParam(intParam) = CStr(strFirstParam)
                Case "Integer", "Int32", "Int16", "int64"
                    objaParam(intParam) = CInt(strSecondParam)
            End Select
        Next intParam
 
        ' This is the line that actually does the work.
        Dim NewObject As Object = Activator.CreateInstance(typToCreate, objaParam)
 
        MsgBox("PropertyOne = " & NewObject.ParameterOne & " (" & NewObject.ParameterTwo & ")")
 
    End Sub
End Class

Open in new window

0
omegaomegaDeveloperCommented:
Hello, Fritz41,

Here is an improved example that should allow for more general parameter types.  I guess if some of the parameters are of class types for which objects need to be created from string names, you could make this into a recursive function.  (The code for Class1 is unchanged from the previous example.)

Cheers,
Randy

Option Strict Off
Imports System.ComponentModel
Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 
        Dim strClassName As String = GetType(Class1).FullName       ' This would come from XML file.
        Dim straParams() As String = {"First Parameter", "1234"}    ' And so would these.
        ' Prepare the information required.
        Dim typToCreate As Type = Type.GetType(strClassName)
        Dim ConstrInfo() As Reflection.ConstructorInfo = typToCreate.GetConstructors
        Dim ParamInfo() As Reflection.ParameterInfo = ConstrInfo(0).GetParameters
        If (straParams IsNot Nothing AndAlso ParamInfo.Length <> straParams.Length) Then
            ' Take care of setting default values for parameters (or throw an exception).
        End If
 
        Dim objaParam() As Object           ' Parameters to pass to constructor.
        If (ParamInfo.Length = 0) Then
            objaParam = Nothing
        Else
            ReDim objaParam(ParamInfo.Length - 1)
            For intParam As Integer = 0 To ParamInfo.Length - 1
                Dim Param As Reflection.ParameterInfo = ParamInfo(intParam)
                Dim typParam As Type = Param.ParameterType
                objaParam(intParam) = TypeDescriptor.GetConverter(typParam).ConvertFromString(straParams(intParam))
            Next intParam
        End If
 
        ' This is the line that actually does the work.
        Dim NewObject As Object = Activator.CreateInstance(typToCreate, objaParam)
 
        ' This is just to show that the object was actually created.
        MsgBox("PropertyOne = " & NewObject.ParameterOne & " (" & NewObject.ParameterTwo & ")")
 
    End Sub
 
End Class

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fritz41Author Commented:
Hi Randy. Thanks for the excellent solution. It appears the line I was missing in my own "research" was Type.GetType(). I have one comment, which I will paste for general reading below. Thanks again!
0
Fritz41Author Commented:
Hi Randy. Thanks, I tried your solution and it works fine. One comment, though. As I see it, the line:

Dim strClassName As String = GetType(Class1).FullName    

will not work, as Class1 needs to be a type name, it cannot be a string value (eg "myClass"). But for my needs, your solution kicks in from the line:

Dim typToCreate As Type = Type.GetType(strClassName)

Because my class name is a string that comes from the XML file (eg. <classToCreate>myNamespace.myProject.MyClass</classToCreate>
In any event, your code solved my problem. Thanks also for the update on a generic method to get the right parameter type, I must have used the Select Case stand-in code 100 times!

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.