Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

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 *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips