?
Solved

Creating a class instance using a string name

Posted on 2008-11-13
4
Medium Priority
?
861 Views
Last Modified: 2013-11-08
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.
0
Comment
Question by:Fritz41
  • 2
  • 2
4 Comments
 
LVL 12

Expert Comment

by:omegaomega
ID: 22957451
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
 
LVL 12

Accepted Solution

by:
omegaomega earned 500 total points
ID: 22961826
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
 

Author Closing Comment

by:Fritz41
ID: 31516620
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
 

Author Comment

by:Fritz41
ID: 22962229
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses
Course of the Month13 days, 20 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question