How to write your own method that accepts a callback in VB.NET

1 Answer

0 votes
Imports System

Public Class CallbackMethod

    ' This method receives:
    ' 1. an int array
    ' 2. a callback function (Action(Of Integer)) that will be applied to each element
    Public Shared Sub ApplyToArray(arr As Integer(), callback As Action(Of Integer))
        For Each item In arr
            callback(item)   ' Execute the callback on each array element
        Next
    End Sub

    Public Shared Sub Main(args As String())
        Dim arr() As Integer = {5, 10, 15, 30}

        ' Call ApplyToArray and pass a lambda callback:
        ' For each element x, print x / 5
        ApplyToArray(arr, Sub(x) Console.WriteLine(x / 5))

        Array.ForEach(arr, Sub(n) Console.Write(n & " "))
    End Sub

End Class



'
' run:
'
' 1
' 2
' 3
' 6
' 5 10 15 30 
'

 



answered Mar 20 by avibootz
...