Understanding Delegates using Visual Basic.NET 2005 - A simple introduction Continued
(Page 2 of 6 )
In the previous section, a class named "Sample01" was introduced. The following is a simple "delegate" way of coding:
'sample of using delegate
Public Class Form2
Delegate Sub Calculate()
Dim obj As New Sample01(10, 20)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim delg As New Calculate(AddressOf obj.Add)
delg.Invoke()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim delg As New Calculate(AddressOf obj.Multiply)
delg.Invoke()
End Sub
End Class
Let us try to understand it step by step. First of all we have the following:
Delegate Sub Calculate()
The line says that "Calculate" is a delegate. Even though its signature looks like a method, it is actually a class. Consider "Calculate" to be a named class of yours having its own functionality to invoke "methods of other objects dynamically."
Further proceeding we have the following:
Dim obj As New Sample01(10, 20)
It is simply an instantiation. Further on we have the following:
Dim delg As New Calculate(AddressOf obj.Add)
As previously described, "Calculate" is a class. And now, "delg" is an instance of the class "Calculate," which is "authorized" to access and execute the method named "obj.Add()".
The "obj.Add()" method gets executed when the following statement is invoked:
delg.Invoke()
Finally, a delegate is simply an object which can execute methods of other objects dynamically at run time.
To make all of this simpler, the above can also be written as follows:
'without creating instances of a delegate and without using invoke
Public Class Form3
Delegate Sub Calculate()
Dim obj As New Sample01(10, 20)
Dim deleg As Calculate
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
deleg = AddressOf obj.Add
deleg()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
deleg = AddressOf obj.Multiply
deleg()
End Sub
End Class
Next: Delegates with parameters using Visual Basic 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee