Dyrdek
Dyrdek

Reputation: 429

Dynamic Class Instantiation in VB (System.Windows.Forms)

I need a dynamic class instantiation in VB. I get a string like "System.Windows.Forms.TextBox" and dynamically depending on that string set the type of my object to TextBox.

I already tried "Activator.CreateInstance(...)" and "CallByName(...)" but I wasn't able to make it work.

Anybody has an idea how this could work?

Thanks

Upvotes: 0

Views: 708

Answers (1)

Alessandro Mandelli
Alessandro Mandelli

Reputation: 581

Public Function CreateClass(ByVal className As String) As Object

    Dim asms() As Assembly = AppDomain.CurrentDomain.GetAssemblies

    For Each Asm As Assembly In asms
        Dim types = Asm.GetTypes

        For Each T As Type In types
            If T.Name.Equals(className, StringComparison.OrdinalIgnoreCase) Then
                Return Activator.CreateInstance(T)
            End If
        Next

    Next

    Throw New Exception("Type not found")
End Function

Upvotes: 1

Related Questions