Saturday, May 7, 2011

Using Delegates in Vb.Net


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


No comments: