How to Use Delegates in Vb.Net

In this article I will try to explain you the basics of Delegate in VB.Net.
  • 15609

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. The following example declares a delegate named mydlg that can encapsulate a method :

How we use delegate in 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)

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

The following code define the delegate:

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 : ")


    End Sub



    Sub Main()

        Dim dlg As mydel

        dlg = New mydel(AddressOf message)


        Dim dlg1 As mydel1

        dlg1 = New mydel1(AddressOf add)




    End Sub


End Module





Hope this article would have helped you in understanding Delegates in VB.NET.


More Articles

© 2020 DotNetHeaven. All rights reserved.