ARTICLE

Using Delegates in Vb.Net

Posted by Rohatash Kumar Articles | Visual Basic 2010 August 16, 2010
In this article I will try to explain you the basics of Delegate in VB.Net.
 
Reader Level:

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 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.

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

        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:

del.gif


 

Conclusion:

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

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor