VB.NET Delegates and Events

In this article I will explain about Delegates and Events in VB.NET.
  • 4672
Download Files:
 

A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. Although delegates have other uses, the discussion here focuses on the event-handling functionality of delegates.

Events in VB.NET are handled by delegates, which serve as a mechanism that defines one or more callback functions to process events. An event is a message sent by an object to signal the occurrence of an action. The action could arise from user interaction, such as a mouse click, or could be triggered by some other program logic. The object that triggers the event is called the event sender. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will handle the events it raises. It merely functions as an intermediary or pointer-like mechanism between the source and the receiver, as illustrated in Listing 5.47. The .NET framework defines a special type delegate that serves as a function pointer.

Listing 5.47: DelegateEvent.VB, Delegates and Events Example


Public
Class MyEvt
    Public Delegate Sub t(ByVal sender As [Object], ByVal e As MyArgs)
    ' declare a delegate 
    Public Event tEvt As t
    'declares an event for the delegate
    Public Sub mm()
        'function that will raise the callback
        Dim r As New MyArgs()
        RaiseEvent tEvt(Me, r)
        'calling the client code
    End Sub 
    Public Sub New()
    End Sub
End Class
'arguments for the callback
Public Class MyArgs
    Inherits EventArgs
    Public Sub New()
    End Sub
End Class
Public Class MyEvtClient
    Private oo As MyEvt
    Public Sub New()
        Me.oo = New MyEvt()
        AddHandler Me.oo.tEvt, New MyEvt.t(AddressOf oo_tt)
    End Sub 
    Public Shared Sub Main(ByVal args As [String]())
        Dim cc As New MyEvtClient()
        cc.oo.mm()
    End Sub 
    'this code will be called from the server 
    Public Sub oo_tt(ByVal sender As Object, ByVal e As MyArgs)
        Console.WriteLine("yes")
        Console.ReadLine()
    End Sub
End Class

de.gif

Conclusion

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

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.