Delegate

Delegate is type which holds the method(s) reference in an object, similar to a function pointer in C and C++, delegates are object-oriented, type safe, and secure.

Multicast Delegate

It is a Delegate which holds the reference of more than one methods.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

How we use delegate in VB.net programming:

public delegate sub mydlg()

Then we use the delegate by simply declaring a variable of the delegate and assigning the sub or function to run when called. First the sub to be called:

Private Sub message()
Console.WriteLine ( "show message" )
End Sub

now it matches our declaration of MyDlg. it's a sub routine with no parameters. And then our test code:

Dim dlg As mydel
dlg = New mydel(AddressOf message)
dlg.Invoke()

When we invoke the delegate, the message sub is run.

For example

Module Module1

Public Delegate Sub mydel()

Public Delegate Sub mydel1(ByVal a As Integer)

Public Sub message()

Console.WriteLine("show message")

End Sub

Public Sub add(ByVal a As Integer)

Dim b As Integer

b = a + a

Console.Write(" Addition is : ")

Console.WriteLine(b)

End Sub

Sub Main()

Dim dlg As mydel

dlg = New mydel(AddressOf message)

dlg.Invoke()

Dim dlg1 As mydel1

dlg1 = New mydel1(AddressOf add)

dlg1.Invoke(10)

End Sub

End Module

OUTPUT

d1.gif