Delegates In VB.NET
How to use Delegates?
Explanation
Delegates in vb.net 2008.
Delegates are pointers that are used to store and tranfer information like the memory address, event handled by
functions and subroutines. Delagates are type safe, since they check for the signatures of functions and subroutines
only if same, they transfer information. A delegate is declared using the keyword Delegate to a function
or procedure name.
Example:
Module Module1
Public Delegate Function del1(ByVal x As Integer,
ByVal y As Integer) As Integer
Public Delegate Sub Display()
Public Function check(ByVal x As Integer,
ByVal y As Integer) As Integer
Return (x + y)
End Function
Public Function multi(ByVal x As Integer,
ByVal y As Integer) As Integer
Return (x * y)
End Function
Class deleg
Public Sub Disp()
Console.WriteLine("Method inside the Class")
End Sub
End Class
Sub Main()
Dim a As New del1(AddressOf check)
Dim b As New del1(AddressOf multi)
Dim ob As New deleg
Dim c As New Display(AddressOf ob.Disp)
Console.WriteLine(a(10, 20))
Console.WriteLine(b(10, 20))
c()
Console.Read()
End Sub
End Module
Result:
30
200
Method Inside Class
Description:
In the above Delegate example
del1 is a delegate that gets two integer arguments and return an integer.
Using this delegate with the keyword
AddressOf the values stored in the memory location of the procedures
check
and
multi are retreived.
Using the delegate
Display the sub procedure
Disp() inside the class
deleg is also
displayed.