w0051977
w0051977

Reputation: 15817

Reflection - creating datatype from a string literal value

Please see the code below:

Public Function Test()
    Dim o As Object = getVariable("Integer")
    If TypeOf o Is Integer Then
        'Do some processing on the integer
    ElseIf TypeOf o Is Decimal Then
        'Do some processing on the integer
    End If
End Function

Public Function getVariable(ByVal strDataType As String)
    If strDataType = "Integer" Then
        Return New Integer
    ElseIf strDataType = "Decimal" Then
        Return New Decimal
    ElseIf strDataType = "Double" Then
        Return New Double
    End If
End Function

I suspect there is an easier way (fewer lines of code) of doing this with Reflection?

Upvotes: 0

Views: 135

Answers (2)

jcwrequests
jcwrequests

Reputation: 1130

The real question is what ars you trying to solve? Activator will work. Are trying to create a factory or an IOC container. Could you provide more detail? You could also create a dictionary were the key is of type string and then item stores delegates used to actual create the type.

Upvotes: 0

Victor Zakharov
Victor Zakharov

Reputation: 26444

You can use Type.GetType together with Activator.CreateInstance:

Public Function getVariable(ByVal strDataType As String)
  Return Activator.CreateInstance(Type.GetType(strDataType))
End Function

For strDataType you need to be using System.Int32, System.Decimal and System.Double respectively. If you want to keep it as Integer etc., you need to incorporate string translation, for example, have a Dictionary(Of String, String), with entries like ("Integer", "System.Int32").

Upvotes: 3

Related Questions