Visual Basic Language Reference  

Delegate Statement

Used to declare a delegate. Delegates are a reference type that refers to a Shared method of a type or to an instance method of an object. Any procedure with matching parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be invoked via the delegate instance.

[ <attrlist> ] [ Public | Private | Protected | Friend | Protected Friend ] _
[ Shadows ] DelegateSub ] name [([ arglist ])]

-or-

[ <attrlist> ] [ Public | Private | Protected | Friend | Protected Friend ] _
[ Shadows ] Delegate [ Function ] name [(arglist ])] As type

Parts

attrlist
Optional. List of attributes that apply to this delegate. Multiple attributes are separated by commas.
Public
Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private
Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected
Optional. Entities declared with the Protected keyword have protected access. They are accessible only from within their own class or from a derived class. Protected access can be specified only on members of classes. It is not a superset of friend access.
Friend
Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend
Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
Shadows
Optional. Indicates that this delegate shadows an identically named programming element in a base class. You can shadow any kind of declared element with any other kind. A shadowed element is unavailable in the derived class that shadows it
Sub
Optional, but either Sub or Function must appear. Declares this procedure as a delegate subroutine that does not return a value.
Function
Optional, but either Sub or Function must appear. Declares this procedure as a delegate function that returns a value.
name
Required. Name of the delegate type; follows standard variable naming conventions.
arglist
Optional. List of variables representing arguments that are passed to the procedure when it is called.
type
Optional. Data type of the return value.

Each attribute in the attrlist part has the following syntax and parts:

attrname [({ attrargs | attrinit })]

attrlist Parts

attrname
Required. Name of the attribute. Must be a valid Visual Basic identifier.
attrargs
Optional. List of positional arguments for this attribute. Multiple arguments are separated by commas.
attrinit
Optional. List of field or property initializers for this attribute. Multiple initializers are separated by commas.

Each argument in the arglist part has the following syntax and parts:

[ <attrlist> ] [ ByVal | ByRef ] varname[( )] [ As type ]

arglist Parts

attrlist
Optional. List of attributes that apply to this argument. Multiple attributes are separated by commas.
ByVal
Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic.
ByRef
Optional. Indicates that the argument is passed by reference.
varname
Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
( )
Required for array variables. Indicates that varname is an array.
type
Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String (variable length only), Object, a user-defined type, or an object type.

Remarks

The Delegate statement defines the parameter types and return type of a delegate class. Any procedure with matching parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be invoked via the delegate instance, by calling the delegate's Invoke method.

Each delegate class defines a constructor that is passed the specification of an object method. The only thing that can be legally specified as an argument to such a delegate constructor is an expression of the form:

AddressOf [<expression>.]<methodname>

The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an instance method. The methodname is not optional even if you create a delegate for the default method of the class.

Example

This example uses the Delegate statement to declare a delegate for comparing two integers and returning a Boolean. The SelectionSort method takes an instance of a delegate of this type and uses it to sort an integer array.

Public Class SortClass
   Delegate Function Compare(ByVal x As Integer, _
                                 ByVal y As Integer) As Boolean

   Function CompareValues(ByVal X As Integer, _
                          ByVal Y As Integer) As Boolean
      If X > Y Then
         CompareValues = True
      Else
         CompareValues = False
      End If
   End Function

   Sub SelectionSort(ByVal IsGreaterThan As Compare, _
                     ByVal IntArray() As Integer)
      Dim MaxVal As Integer
      Dim MaxIndex As Integer
      Dim i, j As Integer

      ' Step through the elements in the array starting with the
      ' last element in the array.
      For i = UBound(IntArray) To 1 Step -1
         MaxVal = IntArray(i)
         MaxIndex = i
         For j = 1 To i
            ' Use the delegate to compare values.
            If IsGreaterThan.Invoke(IntArray(j), MaxVal) Then
               MaxVal = IntArray(j)
               MaxIndex = j
            End If
         Next j
         ' Use the delegate to compare values.
         If IsGreaterThan.Invoke(i, MaxIndex) Then
            IntArray(MaxIndex) = IntArray(i)
            IntArray(i) = MaxVal
         End If
      Next i
   End Sub
End Class

Class Class1
   Sub SortArray()
      Dim Sort As New SortClass()
      Dim arr1() As Integer = {1, 5, 3, 2, 7, 22, 5, 54, 12}
      Sort.SelectionSort(AddressOf Sort.CompareValues, arr1)
      MsgBox("Array sorted.")
   End Sub
End Class

' Add a button to your main form and insert the following code
' into the Click event handlr. 
   Private Sub Button1_Click(ByVal sender As System.Object, _
                             ByVal e As System.EventArgs) _
                             Handles Button1.Click
      Dim c As New Class1()
      c.SortArray()
   End Sub

See Also

Events and Delegates