This documentation is archived and is not being maintained.

Delegate Example

You can use delegates for other, non-event related tasks, such as free threading or with procedures that need to call different versions of functions at compile time.

For example, suppose you have a classified-ad application that includes a list box with the names of cars. The ads are sorted by title, which is normally the make of the car. A problem you may face occurs when some cars include the year of the car before the make. The problem is that the built-in sort functionality of the list box sorts only by character codes; it places all the ads starting with dates first, followed by the ads starting with the make.

To fix this, you can create a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to switch at run time to the custom sort procedure for car ads. To do this, you pass the custom sort procedure to the sort class at run time, using delegates.

Each delegate class defines a constructor that is passed the specification of an object method. The following code provides an example of a parameter to such a delegate constructor:

AddressOf [<expression>.]<method name>

The compile-time type of the expression must be a class or an interface with a method by the specified name whose signature matches the signature of the delegate class. The method can be either a shared (class) method or an instance method.

You invoke the method associated with a delegate instance by calling its built-in Invoke method, as illustrated in the following example:

Delegate Sub MySubDelegate(ByVal x As Integer)
Protected Sub Test()
   Dim c2 As New class2()
   ' Test the delegate.
End Sub

Class class1
   Sub Sub1(ByVal x As Integer)
      MessageBox.Show("The value of x is: " & CStr(x))
   End Sub
End Class

Class class2
   Sub DelegateTest()
      Dim c1 As Class1
      Dim msd As MySubDelegate
      c1 = New Class1()
      ' Create an instance of the delegate.
      msd = AddressOf c1.Sub1
      msd.Invoke(10) ' Call the method.
   End Sub
End Class

See Also

Delegate Statement | Delegates and the AddressOf Operator | Events and Event Handlers | AddHandler and RemoveHandler | Writing Event Handlers | Multithreaded Applications