Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Passing Delegates as Arguments

The classic example of procedural types is to pass the address of functions to sorting algorithms. As in the "Hello World!" examples, it's almost tradition to demonstrate procedural types using sort algorithms. In this section I will demonstrate three sort algorithms that use one of two comparison functions to alternate between ascending and descending sort order.

To demonstrate passing Delegate arguments, I will guide you through the construction of SortAlgorithms.sln (contained on this book's companion web site, and shown in Figure 2). To complete the sample program, we will define a Compare Delegate that compares two integers. To perform comparisons based on a user preference of ascending or descending order, we will define two compare procedures suitably named Greater and Less. Listing 7 shows just the Delegate definition and two function definitions. Listing 8 contains the complete SortAlgorithms.sln listing (except for the Windows Form Designer–generated code).

Figure 2 The SortAlgorithms application showing BubbleSort swaps in progress.

Listing 7—The Delegate Definition and Two Suitable Functions for Instances of the Compare Delegate

 1: Delegate Function Compare(ByVal Height1 As Integer, _
 2:  ByVal Height2 As Integer) As Boolean
 3:
 4: Public Function Greater(ByVal H1 As Integer, _
 5:  ByVal H2 As Integer) As Boolean
 6:  Return H1 > H2
 7: End Function
 8:
 9: Public Function Less(ByVal H1 As Integer, _
10:  ByVal H2 As Integer) As Boolean
11:  Return H1 < H2
12: End Function

Notice that the Delegate procedural value is defined as a function that takes two integers and returns a Boolean. The signatures of Greater and Less precisely match the definition of the Delegate. To declare and initialize an instance of the Compare Delegate, do so in a Dim statement such as this:

Dim LessCompare As Compare = AddressOf Less

Referring to Figure 2, the sort order is indicated by the state of the Ascending checkbox shown in the lower-right corner of the main form in Figure 2. If the box is checked, the address of the Less function will be passed to the algorithm; otherwise, the address of the Greater function will be passed to the sort algorithm.

Reviewing the Sort Algorithms and Demo Application Behavior

The basics of sorting algorithms are the mechanisms for iterating, comparing, and swapping the elements of a group of similar data. For the sample program, I added a slight twist: We will iterate, sort, and swap rectangles drawn on a form to allow the user to see the effect of a particular algorithm (and for fun).

The SortAlgorithms application initializes a System.Array of Rectangles with random heights along the top of the form containing the code. The Random generator is invoked on Form_Load (refer to Listing 7) and can be regenerated with the Sort, Randomize menu in the sample program.

Based on the sort selected from the Sort menu—Bubble, Selection, or Quick—a specific sort is run. The iteration algorithms for the sorts are based on classic implementations of these algorithms.

The Compare algorithms compare heights of the rectangles only and swap the actual rectangles and rectangle heights because all other coordinates of the rectangles are relative to the top-left corner of the form. See Listing 8 for the complete implementation.

Sort Algorithms

The three sort algorithms were chosen because they are quite common. The Bubble sort uses a nested For loop, comparing and swapping each element where the ith element is less than or greater than the ith + n element, depending on the order of the sort. A Bubble sort performs n2 comparisons and possibly the same number of swaps (refer to BubbleSort in Listing 8).

The Selection sort is essentially a Bubble sort. Slightly better performance characteristics are achieved because the Selection sort only performs n-swaps (refer to SelectionSort in Listing 8).

The Quick sort has Log2n, or logarithmic, performance characteristics. Performance decay of a Quick sort occurs very slowly, making the Quick sort a good general-purpose, fast sort. Quick sort performance decays in highly ordered sets, with results on ordered sets decaying to those of a Selection sort (refer to QuickSort in Listing 8).

Walking Through the SortAlgorithms Demo Application

We have covered the basic steps in defining the SortAlgorithms application. Listing 8 contains the complete listing of the demo application. A synopsis follows the listing, elaborating on some of the other examples of using delegates contained in the actual solution.

Listing 8—The SortAlgorithms Demo Application Uses Procedural Type Arguments with Rectangles and Sorting Algorithms for Context

 1: Public Class Form1
 2:  Inherits System.Windows.Forms.Form
 3:
 4: [ Windows Form Designer generated code ]
 5:
 6:  Private Rectangles(300) As Rectangle
 7:  Private FSortOrder As Boolean
 8:  Private CompareProcs() As Compare = _
 9:   {AddressOf Less, AddressOf Greater}
 10:
 11:  Delegate Function Compare(ByVal Height1 As Integer, _
 12:   ByVal Height2 As Integer) As Boolean
 13:
 14:  Private Function GetCompareProc(ByVal Value _
 15:   As Boolean) As Compare
 16:   Return CompareProcs(Math.Abs(CInt(Value)))
 17:  End Function
 18:
 19:  Private Sub DrawRandomBars()
 20:
 21:   Array.Clear(Rectangles, 0, _
 22:    Rectangles.GetUpperBound(0))
 23:
 24:   Dim I As Integer
 25:
 26:   For I = Rectangles.GetLowerBound(0) To _
 27:   Rectangles.GetUpperBound(0)
 28:    Rectangles(I) = New Rectangle(I * 2, 0, 1, Rnd() * 200)
 29:   Next
 30:
 31:   Invalidate()
 32:  End Sub
 33:
 34:  Private Sub ConditionalInvalidate()
 35:   If (Not CheckBoxShowSwaps.Checked) Then _
 36:    Invalidate()
 37:  End Sub
 38:
 39:  Private Sub DrawRectangle(ByVal Rect As Rectangle, _
 40:   ByVal APen As Pen)
 41:   CreateGraphics.DrawRectangle(APen, Rect)
 42:  End Sub
 43:
 44:  Private Sub Form1_Paint(ByVal sender As System.Object, _
 45:   ByVal e As System.Windows.Forms.PaintEventArgs) _
 46:   Handles MyBase.Paint
 47:
 48:   Dim Graphics As System.Drawing.Graphics = CreateGraphics()
 49:   Graphics.DrawRectangles(Pens.Green, Rectangles)
 50:
 51:  End Sub
 52:
 53:  Public Function Greater(ByVal H1 As Integer, _
 54:   ByVal H2 As Integer) As Boolean
 55:
 56:   Return H1 > H2
 57:
 58:  End Function
 59:
 60:  Public Function Less(ByVal H1 As Integer, _
 61:   ByVal H2 As Integer) As Boolean
 62:
 63:   Return H1 < H2
 64:
 65:  End Function
 66:
 67:  Public Sub EraseOld(ByVal Rects() As Rectangle, _
 68:   ByVal I As Integer, ByVal J As Integer)
 69:
 70:   If (Not CheckBoxShowSwaps.Checked) Then Exit Sub
 71:   DrawRectangle(Rects(I), Pens.LightGray)
 72:   DrawRectangle(Rects(J), Pens.LightGray)
 73:
 74:  End Sub
 75:
 76:  Public Sub DrawNew(ByVal Rects() As Rectangle, _
 77:   ByVal I As Integer, ByVal J As Integer)
 78:
 79:   If (Not CheckBoxShowSwaps.Checked) Then Exit Sub
 80:   DrawRectangle(Rects(I), Pens.Green)
 81:   DrawRectangle(Rects(J), Pens.Green)
 82:
 83:  End Sub
 84:
 85:  Public Sub Swap(ByVal Rects() As Rectangle, _
 86:   ByVal I As Integer, ByVal J As Integer)
 87:
 88:   EraseOld(Rects, I, J)
 89:
 90:   Dim R As Rectangle
 91:   R = Rects(I)
 92:   Rects(I) = Rects(J)
 93:   Rects(J) = R
 94:
 95:   Dim X As Integer = Rects(I).X
 96:   Rects(I).X = Rects(J).X
 97:   Rects(J).X = X
 98:
 99:   DrawNew(Rects, I, J)
100:  End Sub
101:
102:  Public Sub BubbleSort(ByVal Rects() As Rectangle, _
103:   ByVal CompareProc As Compare)
104:
105:   Dim I, J As Integer
106:   For I = 0 To Rects.GetUpperBound(0) - 1
107:
108:    For J = I + 1 To Rects.GetUpperBound(0)
109:     Application.DoEvents()
110:
111:     If (CompareProc(Rects(I).Height, _
112:     Rects(J).Height)) Then
113:
114:      Swap(Rects, I, J)
115:
116:     End If
117:    Next
118:   Next
119:
120:  End Sub
121:
122:  Public Sub SelectionSort(ByVal Rects() As Rectangle, _
123:   ByVal CompareProc As Compare)
124:
125:   Dim I, J, SwapIndex As Integer
126:
127:   For I = 0 To Rects.GetUpperBound(0) - 1
128:    SwapIndex = I
129:
130:    For J = I + 1 To Rects.GetUpperBound(0)
131:     If (CompareProc(Rects(SwapIndex).Height, _
132:      Rects(J).Height)) Then
133:
134:      SwapIndex = J
135:
136:     End If
137:    Next
138:
139:    Swap(Rects, I, SwapIndex)
140:   Next
141:
142:  End Sub
143:
144:  Public Sub QuickSort(ByVal Rects() As Rectangle, _
145:   ByVal Left As Integer, ByVal Right As Integer, _
146:   ByVal Comp1 As Compare, ByVal Comp2 As Compare)
147:
148:   Dim I, J As Integer
149:   Dim Rect As Rectangle
150:
151:   If (Right > Left) Then
152:    Rect = Rects(Right)
153:    I = Left - 1
154:    J = Right
155:
156:    Do While (True)
157:     Do
158:      I += 1
159:     Loop While (Comp1(Rects(I).Height, Rect.Height))
160:
161:     Do
162:      J = J - 1
163:      If (J < Rects.GetLowerBound(0)) Then Exit Do
164:     Loop While (Comp2(Rects(J).Height, Rect.Height))
165:
166:     If (I >= J) Then Exit Do
167:
168:     Swap(Rects, I, J)
169:    Loop
170:
171:    Swap(Rects, I, Right)
172:    QuickSort(Rects, Left, I - 1, Comp1, Comp2)
173:    QuickSort(Rects, I + 1, Right, Comp1, Comp2)
174:
175:
176:   End If
177:
178:  End Sub
179:
180:  Private Sub Form1_Load(ByVal sender As System.Object, _
181:   ByVal e As System.EventArgs) Handles MyBase.Load
182:
183:   DrawRandomBars()
184:
185:  End Sub
186:
187:  Private Sub MenuExit_Click(ByVal sender As System.Object, _
188:   ByVal e As System.EventArgs) Handles MenuExit.Click
189:
190:   End
191:
192:  End Sub
193:
194:  Private Sub MenuRandomize_Click(ByVal sender As System.Object, _
195:   ByVal e As System.EventArgs) Handles MenuRandomize.Click
196:
197:   DrawRandomBars()
198:
199:  End Sub
200:
201:  Private Sub MenuSelection_Click(ByVal sender As System.Object, _
202:   ByVal e As System.EventArgs) Handles MenuSelection.Click
203:
204:   SelectionSort(Rectangles, _
205:    GetCompareProc(CheckBoxAscending.Checked))
206:
207:   ConditionalInvalidate()
208:  End Sub
209:
210:  Private Sub MenuBubble_Click(ByVal sender As System.Object, _
211:   ByVal e As System.EventArgs) Handles MenuBubble.Click
212:
213:   BubbleSort(Rectangles, _
214:    GetCompareProc(CheckBoxAscending.Checked))
215:
216:   ConditionalInvalidate()
217:  End Sub
218:
219:  Private Sub menuQuick_Click(ByVal sender As System.Object, _
220:   ByVal e As System.EventArgs) Handles menuQuick.Click
221:
222:   QuickSort(Rectangles, Rectangles.GetLowerBound(0), _
223:    Rectangles.GetUpperBound(0), _
224:    GetCompareProc(Not CheckBoxAscending.Checked), _
225:    GetCompareProc(CheckBoxAscending.Checked))
226:
227:   ConditionalInvalidate()
228:  End Sub
229:
230: End Class

NOTE

All of the source code for this book is contained on the accompanying companion web site. For that reason, in general, long listings will be avoided. However, Listing 8 demonstrates several programming techniques in context, so it was listed in its entirety to facilitate discussion.

The three sort subroutines—BubbleSort, SelectionSort, and QuickSort—are defined on lines 102 to 178. From the listing, it's apparent that both the Bubble and Selection sorts use a nested For loop. The biggest difference is the point at which swaps are made. The Bubble sort swaps in the inner For loop, and the Selection sort swaps at the end of the outer loop. Important to our discussion is the use of the Delegate Compare as the last argument to each subroutine. This argument is satisfied by passing either AddressOf Greater or AddressOf Less to the CompareProc parameter.

The SortAlgorithms demo passes the sort ordered based on the state of the CheckBoxAscending.Checked property. In the MenuBubble_Click handler, such code might be written as follows:

If( CheckBoxAscending.Checked ) Then
 BubbleSort( Rectangles, AddressOf Greater )
Else
 BubbleSort( Rectangles, AddressOf Less )
End If

To yield a more concise implementation, as opposed to repeating the If conditional code, an array of procedural types was used. The resultant event handler was implemented as follows:

BubbleSort( Rectangles, GetCompareProc( CheckBoxAscending.Checked ))

GetCompareProc is defined as a function that uses a Boolean to index an array of the initialized Delegates. The initialized array of Delegates is defined on lines 8 and 9:

Private CompareProcs() As Compare = _{AddressOf Less, AddressOf Greater}

TIP

Sometimes using arrays of objects, like the Delegate array on lines 8 and 9 of Listing 7, can be a bit esoteric. The use of the wrapper function GetCompareProc may help clear up confusion and provides a convenient place for a block comment, letting less experienced developers in on the secret.

The array CompareProcs is an array of the Delegate Compare initialized to the AddressOf the Less and Greater functions. (Using an array instead of If conditional code generally leads to more concise machine instructions, but this wasn't verified with respect to Visual Basic .NET.) The array of Delegates does demonstrate that it is possible to have an array of complex types, including Delegates. Such an array is a more concise, reasonable alternative to using long If conditional statements or case statements.

The Quick sort —lines 144 to 178—takes two comparisons; it chunks the subset of elements roughly in half recursively, ordering successively smaller subsets of elements. The two delegates are used to switch the order of the sort. Based on the state of the CheckBoxAscending.Checked property, the Compare procedures are flip-flopped in the order in which they are passed. Line 159 uses the argument Comp1 and line 164 uses Comp2. Less is passed to Comp1 if the checkbox is checked and Greater to Comp2. The argument values are switched if the checkbox is unchecked. This swapping of delegates is demonstrated on lines 224 and 225.

Illustrating an Alternative to Procedural Types

The EraseOld subroutine erases an existing rectangle by drawing a masking rectangle over the existing rectangle. The DrawNew subroutine draws the rectangle in its new position. The EraseOld and DrawNew subroutines demonstrate an alternative to procedural arguments. EraseOld and DrawNew are always called in the Swap algorithm; however, the code in them is only run based on the state. Because the state of the CheckBoxShowSwaps.Checked property is checked potentially thousands of times each time Swap is called, EraseOld and DrawNew add to a sort algorithm's decay based on the number of swaps. The two methods demonstrate how conditional behavior has always been handled in the absence of procedural types: Check the conditional value each time.

Delegates used to implement dynamic behavior allow you to write code that evaluates a condition one time and then act on that state condition until the state condition changes. Using the delegates, your code only has to evaluate the desired sort order one time, prior to calling a sort algorithm. Use the conditional code without the delegates and, as is the case with the Bubble sort, your code will evaluate the state condition possibly millions of times. In a production system, a couple of million extra conditional checks will make a big difference.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020