Uses delegates to sort random numbers (ascending or descending) : Delegate « Class Module « VB.Net Tutorial






Public Class Tester


   Private Shared Function SortAscending(ByVal element1 As Integer, _
      ByVal element2 As Integer) As Boolean

      Return element1 > element2
   End Function ' SortAscending

   Private Shared Function SortDescending(ByVal element1 As Integer, _
      ByVal element2 As Integer) As Boolean

      Return element1 < element2
   End Function ' SortDescending

   Public Shared Sub Main
      Dim mBubbleSort As New BubbleSort()

      Dim mElementArray As Integer() = New Integer(9) {}

      Dim randomNumber As Random = New Random()
      Dim i As Integer

      ' create String with 10 random numbers
      For i = 0 To mElementArray.GetUpperBound(0)
         mElementArray(i) = randomNumber.Next(100)
         Console.WriteLine(mElementArray(i))
      Next
    
      mBubbleSort.SortArray(mElementArray, AddressOf SortAscending)

      For i = 0 To mElementArray.GetUpperBound(0)
         Console.Write(mElementArray(i) & " " )
      Next
      Console.WriteLine()
      mBubbleSort.SortArray(mElementArray, AddressOf SortDescending)

      For i = 0 To mElementArray.GetUpperBound(0)
         Console.Write(mElementArray(i) & " " )
      Next

   End Sub

End Class

Public Class BubbleSort
   Public Delegate Function Comparator( _
      ByVal element1 As Integer, _
      ByVal element2 As Integer) As Boolean

   Public Sub SortArray(ByVal array As Integer(), _
      ByVal Compare As Comparator)

      Dim i, pass As Integer

      For pass = 0 To array.GetUpperBound(0)

         For i = 0 To array.GetUpperBound(0) - 1
            If Compare(array(i), array(i + 1)) Then
               Swap(array(i), array(i + 1))
            End If
         Next ' inner loop
      Next ' outer loop
   End Sub ' SortArray

   Private Sub Swap(ByRef firstElement As Integer, _
      ByRef secondElement As Integer)

      Dim hold As Integer

      hold = firstElement
      firstElement = secondElement
      secondElement = hold
   End Sub ' Swap
End Class
77
24
72
44
64
75
23
44
93
73
23 24 44 44 64 72 73 75 77 93
93 77 75 73 72 64 44 44 24 23 "








6.28.Delegate
6.28.1.Define delegate
6.28.2.Define a delegate to be a pointer to a subroutine that has a string parameter.
6.28.3.Use Delegate Sub
6.28.4.Delegate Function
6.28.5.Uses delegates to sort random numbers (ascending or descending)
6.28.6.Use AddressOf to assign function to a delegate
6.28.7.Comparison method based on delegate
6.28.8.Multiple Delegates
6.28.9.Math delegation
6.28.10.Use one Delegate to reference two different functions
6.28.11.Reference a method that has one parameter and returns a value: Func<(Of <(T, TResult>)>)