- Back to Home »
- VB.NET »
- VB.NET Delegates - Single cast delegate and multicast delegates
Posted by :
Sudhir Chekuri
Saturday, 5 October 2013
VB.NET Delegates
Delegate is a type that can hold reference of more than one method.
Signature of the methods should match with the signature of delegate.
VB.NET Single cast delegate
Single cast delegate is used to hold the reference of a single method.
It can have return type.
VB.NET Single cast delegate program
Module module1
Public Class class1
Public Function add(ByVal a As Integer, ByVal b As Integer)
Return a + b
End Function
End Class
'create delegate
Public Delegate Function mydelegate(ByVal a As Integer, ByVal b As Integer) As Integer
Sub main()
'create obj for class1
Dim c1 As New class1()
'create obj for delegate
Dim md As New mydelegate(AddressOf c1.add)
Console.WriteLine("Enter A value")
Dim a As Integer = Console.ReadLine()
Console.WriteLine("Enter B value")
Dim b As Integer = Console.ReadLine()
Console.WriteLine("ADD res is " & md(a, b))
Console.ReadLine()
End Sub
End Module
Output
Enter A value
2
Enter B value
3
ADD res is 5
Multicast delegate
It is capable of holding more than one method.
Signature of methods should match with the signature of the delegate.
void should be the return type of delegate and methods.
VB.NET Multicast delegate program
Module Module1
Delegate Sub display(ByVal a As Integer, ByVal b As Integer)
Dim listofmet(3) As display
Public Sub add(ByVal a As Integer, ByVal b As Integer)
Console.WriteLine(a + b)
End Sub
Public Sub mul(ByVal a As Integer, ByVal b As Integer)
Console.WriteLine(a * b)
End Sub
Public Sub div(ByVal a As Integer, ByVal b As Integer)
Console.WriteLine(a / b)
End Sub
Public Delegate Sub mydel(ByVal a As Integer, ByVal b As Integer)
Sub Main()
listofmet(0) = New display(AddressOf add)
listofmet(1) = New display(AddressOf mul)
listofmet(2) = New display(AddressOf div)
Dim del As New display(AddressOf add)
del = display.Combine(listofmet)
del.Invoke(12, 12)
Console.ReadLine()
End Sub
End Module
Ouput
24
144
1
Thanks for sharing! My university Follow Your Blogs To Teaching!!
ReplyDelete