×

VB.Net Programs

VB.Net program to call multiple methods using a single-cast delegate

By Nidhi Last Updated : October 13, 2024

Calling multiple methods using a single-cast 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. The delegate is similar to the function pointer in C. It holds the address of the function. We can call the function using delegates.

Program/Source Code:

The source code to call multiple methods using the single-cast delegate is given below. The given program is compiled and executed successfully.

VB.Net code to call multiple methods using a single-cast delegate

'VB.net program to handle multiple methods 
'using single caste 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
    Sub Main()
        Dim cal As New CalC()

        Dim del As MyDelegate = AddressOf cal.Addition
        del(20, 10)

        del = AddressOf cal.Subtraction
        del(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 Main() method, the Main() method is the entry point for the program. And, we created an object of the CalC class and then assigned the address of methods to the delegate one by one and call methods to perform addition and subtraction of numbers.

VB.Net Basic Programs »


Comments and Discussions!

Load comments ↻





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