Can I pass a class reference as a parameter to a function in VBNet?

mindofsound picture mindofsound · Jun 9, 2013 · Viewed 11.7k times · Source

Please forgive me if I use improper terminology or sound like a complete noob.

When calling a sub in a class library, I'd like to pass not an instantiated form, but just a reference to the class that represents the form. Then I want to instantiate the form from within the class library function. Is this possible?

Something like the following:

In the main application:

ClassLib.MyClass.DisplayForm(GetType(Form1))

Then, in the class library:

Public Class MyClass

    Public Shared Sub DisplayForm(WhichFormClass As Type)
        Dim MyForm as Form = WhichFormClass.CreateObject() 'Getting imaginitive
        MyForm.ShowDialog()
    End Sub

End Class

Hopefully my example conveys what I'm trying to accomplish. If you think my approach is bogus, I'm open to alternative strategies.

Answer

Nico Schertler picture Nico Schertler · Jun 9, 2013

Additionally to MotoSV's answer, here is a version that uses only generics:

Public Shared Sub DisplayForm(Of T As {New, Form})()
    Dim instance = New T()
    instance.ShowDialog()
End Sub

Which you can use like:

DisplayForm(Of Form1)()

With this approach you can be sure that the passed type is a form and that the instance has the ShowDialog() method. There is no cast necessary that might fail eventually. However, it is necessary to know the type parameter at design time in order to call the method.