0

I have this method signature

Public Function As CreateWorkItem(Of T)() As WorkItem

What is the correct way to invoke this method having string representation of T"?

My failed attempt (simplified for clarity):

Dim controllerType As Type = Type.GetType("AccountingController")
CreateWorkItem(Of controllerType)()
E-Bat
  • 4,792
  • 1
  • 33
  • 58
  • 1
    possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nemesv Dec 20 '14 at 21:52

1 Answers1

0

Use a shared factory method instead of generics:

  Public Class WorkItem
    Property MyProperty As String
    Public Shared Function CreateWorkItem(TypeName As String) As WorkItem
      Static sstrNamespace As String = ""
      If sstrNamespace = "" Then
        sstrNamespace = GetType(WorkItem).FullName
        sstrNamespace = sstrNamespace.Substring(0, sstrNamespace.Length - 8) '"WorkItem"=8 characters
      End If
      Dim strFullName As String = sstrNamespace & TypeName 'assume qualified namespace of subclasses are the same as the WorkItem base class
      Dim wi As WorkItem = Nothing
      Try
        wi = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(strFullName)
      Catch ex As Exception
      End Try
      Return wi
    End Function
  End Class

  Public Class AccountingController
    Inherits WorkItem
    Sub New()
      Me.MyProperty = "AccountingController"
    End Sub
  End Class

  Public Class SomethingElse
    Inherits WorkItem
    Sub New()
      Me.MyProperty = "SomethingElse"
    End Sub
  End Class

  Sub Main()
    Dim wi As WorkItem = WorkItem.CreateWorkItem("AccountingController")
    MsgBox(wi.MyProperty)
    Dim wi2 As WorkItem = WorkItem.CreateWorkItem("SomethingElse")
    MsgBox(wi2.MyProperty)
  End Sub
SSS
  • 4,807
  • 1
  • 23
  • 44
  • The select case part will defeat the purpose of generic in this case because i want to use the class without needing to know what type of controller is coming in. The string name of the class comes from database. – E-Bat Dec 22 '14 at 06:15
  • OK, I have reworked it to use reflection to create the class, to avoid the SELECT CASE. I still think a factory method is a better solution than using generics – SSS Dec 22 '14 at 06:52