Referring to a function

2009-10-14

Delegates are used to refer to a function. You define a delegate class (one row) using the keyword Delegate, and when it is created, or instantiated, the instance refers to a function. The code that reaches the delegate instance, can call the function it refers to, no matter if it reaches the function itself. This is a very simple example in a form:

Public Class Form1

    Friend Delegate Sub MyDelegateClass()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim X As New MyDelegateClass(AddressOf Me.DoSomething)
        X()
        X()
    End Sub

    Private Sub DoSomething()
        MessageBox.Show("Hello!")
    End Sub

End Class

The result of this code is of course that the message box is shown twice. In this example, I don’t accomplish anything with the delegate, because I could have called the function DoSomething directly, but delegates can be used to pass functions as parameters or for thread shifting (se the InvokeRequired property).

If I want, I can use the Function keyword to add a anonymous function to the delegate constructor instead of a the name of a existing function.

Public Class Form1

    Friend Delegate Sub MyDelegateClass()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim X As New MyDelegateClass(Function() MessageBox.Show("Hello"))
        X()
        X()
    End Sub

End Class

The limitation of anonymous functions in Visual Basic 9 is that they only can contain one statement. It can still be used to do pretty good functional programming. Parameters are supported.

If I was to pass a function as a parameter to another function, the type of the parameter would be the delegate class, like this:

Public Class Form1

    Friend Delegate Sub MyDelegateClass()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim X As New MyDelegateClass(Function() MessageBox.Show("Hello"))
        Me.CallSomething(X)
    End Sub

    Private Sub CallSomething(ByVal X As MyDelegateClass)
        X()
        X()
    End Sub

End Class

Again, the result will be that two message boxes are shown.

Categories: Visual Basic 9

Tags: Delegates

Leave a Reply

Your email address will not be published. Required fields are marked *



If this is your first comment, it will be moderated before it is shown.