Understanding Delegates using Visual Basic.NET 2005 - Delegates to methods returning values using Visual Basic 2005
(Page 4 of 6 )
In all of the previous examples, I concentrated only on methods which do not return any values. Now, let us concentrate on delegates which can be used to call methods returning values (say, functions in a class).
Let us add one more class as follows:
Public Class Sample03
Private _x As Integer
Private _y As Integer
Public Sub New()
End Sub
Public Sub New(ByVal a As Integer, ByVal b As Integer)
_x = a
_y = b
End Sub
Public Property X() As Integer
Get
Return _x
End Get
Set(ByVal value As Integer)
_x = value
End Set
End Property
Public Property Y() As Integer
Get
Return _y
End Get
Set(ByVal value As Integer)
_y = value
End Set
End Property
Public Function GetSum() As Integer
Return (Me.X + Me.Y)
End Function
Public Function GetProduct() As Integer
Return (Me.X * Me.Y)
End Function
End Class
The above class contains two methods, "GetSum()" and "GetProduct()," which return values of type integer. To access those methods using delegates, you can code as follows:
'delegates to functions
Public Class Form5
Delegate Function Calculate() As Integer
Dim delegCalc As Calculate
Dim obj As New Sample03(10, 20)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
delegCalc = AddressOf obj.GetSum
MessageBox.Show("Sum = " & delegCalc())
'MessageBox.Show("Sum = " & delegCalc.Invoke())
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
delegCalc = AddressOf obj.GetProduct
MessageBox.Show("Product = " & delegCalc())
'MessageBox.Show("Product = " & delegCalc.Invoke())
End Sub
End Class
Next: Callbacks using Delegates >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee