vb.net use function from other form


Keywords:vb.net 


Question: 

I am in a situation where i have a single helper class that i re-use on most of my forms. and it happens that my helper class needs to call a function from that form as well

Public Class Form1
   Dim hc As HelperClass

   Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      hc = New HelperClass
   End Sub

   Private Sub someForm1Sub()
      'do something
   End Sub
End Class

Public Class Form2
   Dim hc As HelperClass

   Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      hc = New HelperClass
   End Sub

   Private Sub someForm2Sub()
      'do something
   End Sub
End Class

Public Class Form3
   Dim hc As HelperClass

   Private Sub Form3_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      hc = New HelperClass
   End Sub

   Private Sub someForm3Sub()
      'do something
   End Sub
End Class

Public Class HelperClass
   'i need to call here someForm1Sub(), someForm2Sub(), someForm3Sub()
   'but it bases on which form uses this class
End Class

i think that there are many ways to do this. I have read some about delegate function, but i do not know how to pass a delegate to other class. I am using vb.net 2010. Please provide the best way to do this

please reply thanks.


1 Answer: 

You can pass a delegate to a method using the AddressOf keyword. For example,

Public Sub Test()
    ' Make Foo() call the Bar() method.
    Foo(AddressOf Bar)
End Sub

Public Sub Foo(d As Action)
   ' Call the delegate.
   d()
End Sub

Public Sub Bar()
    Console.WriteLine("Bar was called.")
End Sub

But, as you say, there are many ways you could do this. One possible solution which may be a bit nicer than passing delegates (especially if there are a few methods in the form that could be called by the helper class) would be to have Form1, Form2 and Form3 all implement an interface, and have the HelperClass call a method on the interface. An instance of the interface could then be given to HelperClass in its constructor.

For example,

Public Interface IForm

    Sub DoStuff()

End Interface


Public Class Form2
    Implements IForm


    Dim hc As HelperClass


    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        hc = New HelperClass(Me)
    End Sub

    Public Sub DoStuff() Implements IForm.DoStuff
        ' Do stuff here.
    End Sub

End Class


Public Class HelperClass

    Private _form As IForm


    Public Sub New(form as IForm)
        _form = form
    End Sub


    Public Sub MakeTheFormDoStuff()
        _form.DoStuff()
    End Sub

End Class