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

12,738

Solution 1

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.

Solution 2

Try

Dim classType As Type = GetType(Form1)

Then call the method:

DisplayForm(classType)

You can then use this type information and reflection to create an instance at runtime in the DisplayForm method:

Activator.CreateInstance(classType)

Note that this is a simple example and performs no error checking, etc. You should read a bit more on reflection to make sure you handle any potential problems.

Edit 1:

Simple example:

Public Class MyClass

    Public Shared Sub DisplayForm(ByVal formType As Type)
        Dim form As Form = DirectCast(Activator.CreateInstance(formType), Form)
        form.ShowDialog()
    End Sub

End Class

You use the method as:

Dim formType As Type = GetType(Form1)
MyClass.DisplayForm(formType)

Again, best to perform some error checking in all of this.

Share:
12,738
mindofsound
Author by

mindofsound

Updated on June 06, 2022

Comments

  • mindofsound
    mindofsound about 2 years

    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.