Dot Net For All

Passing Action, Func And Predicate As Method parameter in VB.NET

Hello Friends, One of the  main use of delegates in .NET framework is that we can pass functions as method parameter. This in turn can help us to call codes across assemblies without referencing each other. In this article I will show you how we can use Action, Func and Predicate as method parameters in VB.NET.

Passing Action delegate as method parameter in VB.NET

In the below code example I am calling an action delegate as Method parameter.

    Sub Main(args As String())
        CreateAndCallDelegate(AddressOf CalledDel)
    End Sub

    Private Sub CalledDel(arg1 As String, arg2 As String)
        Console.WriteLine("I am called")
    End Sub

    Public Sub CreateAndCallDelegate(Del As Action(Of String, String))
        If Not Del Is Nothing Then
            Del("TEst", "Test")
        End If
    End Sub

CreateAndCallDelegate which takes Action delegate as parameter. As we know Action delegate can be used to refer a method up to 16 parameters, I have created with two parameters.

Finally I am calling CreateAndCallDelegate from my Main Sub method by passing CalledDel as method argument. The signature of the CalledDel is same as the action delegate.

One thing you can notice here is that I need to pass delegate with AddressOf keyword.

Passing Action delegate as method parameter in VB.NET

    Sub Main(args As String())
        CreateAndCallDelegate(AddressOf CalledDel)
    End Sub

    Private Function CalledDel(arg2 As String) As String
        Return "I am called"
    End Function

    Public Sub CreateAndCallDelegate(Del As Func(Of String, String))
        If Not Del Is Nothing Then
            Del("Test")
        End If
    End Sub

Similarly above is a small code snippet in VB.NET to have Func delegate as method parameter. The only difference to notice here is, I am passing a method as argument which returns string. 

This was a small post to help understand the syntax and usefulness of action, func and predicate delegates in VB.NET. Specially if we are passing them as method arguments to other Method parameter.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview