Monday, January 16, 2006

Delegates in vb.net

For those of us that are not C# developers we rarely deal with delegates. A delegate is simply a strong typed pointer to a method. C# uses this extensively for wiring of events. VB.NET actually builds the event delegates for us behind the scenes.

Here is a quick example of a simple delegate:

Public Delegate Sub TrafficLightChangedEventHandler(ByVal color As String)

Private Sub TrafficLightChanged(ByVal color As String)
MsgBox(color)
End Sub

Private Sub StartDelegate()
Dim del As TrafficLightChangedEventHandler
del = New TrafficLightChangedEventHandler(AddressOf TrafficLightChanged)
del.Invoke("Red")
End Sub

When startDelegate gets called we create an instance of the Delegate and put in the address of the TrafficLightChanged method which will be called when we run del.invoke("Red"). Note that invoke automatically knew what parameters were required (in this case a color string).

Delegates can also be used to invoke multiple methods with one invoke call. This is often refered to as a MultiCast Delegate.

Public Delegate Sub TrafficLightChangedEventHandler(ByVal color As String)

Private Sub TrafficLightChanged(ByVal color As String)
MsgBox(color)
End Sub

Private Sub TrafficLightChanged2(ByVal color As String)
MsgBox("2: " & color)
End Sub

Private Sub StartDelegate()
Dim del As TrafficLightChangedEventHandler
del = New TrafficLightChangedEventHandler(AddressOf TrafficLightChanged)
del = TrafficLightChangedEventHandler.Combine(New TrafficLightChangedEventHandler (AddressOf TrafficLightChanged), New TrafficLightChangedEventHandler(AddressOf TrafficLightChanged2))
del.Invoke("Red")
End Sub

When we call Invoke() the delegate will execute both TrafficLightChanged and TrafficLightChanged2.

This is exactly how events work in .NET. Raising one event could cause multiple methods to execute that are wired to handle the event.

0 Comments:

Post a Comment

<< Home