VB.Net program to pass a method as a parameter using a delegate

Here, we are going to learn how to pass a method as a parameter using a delegate in VB.Net?
Submitted by Nidhi, on January 03, 2021 [Last updated : March 06, 2023]

Passing a method as a parameter using a delegate in VB.Net

Here, we will create a class with two methods and also declare a delegate according to the signature of methods, both methods must have the same number of parameters and return types. Then we will create a function that accepts delegate name as an argument, and call methods using delegate inside the function.

Program/Source Code:

The source code to pass a method as a parameter using a delegate is given below. The given program is compiled and executed successfully.

VB.Net code to pass a method as a parameter using a delegate

'VB.net program to pass a method as a parameter using a delegate.

Public Delegate Sub MyDelegate(ByVal num1 As Integer, ByVal num2 As Integer)

Class CalC
    Public Sub Addition(ByVal num1 As Integer, ByVal num2 As Integer)
        Dim result As Integer
        result = num1 + num2
        Console.WriteLine("Addition is: {0}", result)

    End Sub

    Public Sub Subtraction(ByVal num1 As Integer, ByVal num2 As Integer)
        Dim result As Integer
        result = num1 - num2
        Console.WriteLine("Subtraction is: {0}", result)
    End Sub
End Class

Module Module1
    Private Sub CallDelegate(ByVal del As MyDelegate, ByVal num1 As Integer, ByVal num2 As Integer)
        del(num1, num2)
    End Sub
    
    Sub Main()
        Dim cal As New CalC()

        CallDelegate(AddressOf cal.Addition, 20, 10)
        CallDelegate(AddressOf cal.Subtraction, 20, 10)
    End Sub
End Module

Output:

Addition is: 30
Subtraction is: 10
Press any key to continue . . .

Explanation:

In the above program, we created a class CalC class that contains two methods Addition() and Subtraction(), and we also declared a delegate according to the signature of methods.

After that, we created a module Module1 that contains the CallDelegate() and Main() functions, The CallDelegate() function accept delegate as an argument and call the methods from delegates. Here, we also pass the address of methods and argument of associated methods.

the Main() method is the entry point for the program. We created the object of CalC class and call methods using delegates.

VB.Net Basic Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.