tutorial

Page 165

{ MessageBox.Show(strTextOutput) } }

There is nothing wrong with this approach at all. In fact, it is probably more commonly used than delegates. However, it does not provide much in terms of flexibility or a dynamic event model. With delegates, you can pass a method along to something else, and let it execute the method instead. Perhaps you do not know which method you want to call until runtime, in which case, delegates also come in handy. Now we will implement the same functionality as before, using a actual delegate class of .NET. Delegates in VB.NET are declared like: Delegate [Function/Sub] methodname(arg1,arg2..argN) The declared delegate methodname will have the same method signature as the methods they want to be a delegate for. This example is calling a shared method.. VB.NET Class VBDelegate 'Declaration of delegate variable with arguments Delegate Function MyDelegate(ByVal strOutput As String) 'Function to call the delegates Public Shared Sub CallDelegates() 'Declare variables of type Mydelegate points to the 'function MessageDisplay with AddressOf operator Dim d1 As New MyDelegate(AddressOf MesssageDisplay) Dim d2 As New MyDelegate(AddressOf MesssageDisplay) 'Pass the arguments to the function through delegates d1("First Delegation ") d2("Second Delegation ") End Sub 'Function to display the message Private Shared Function MesssageDisplay(ByVal strTextOutput As String) MsgBox(strTextOutput) End Function End Class

C#


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.