ProblemYou want to process all the elements of an array without the overhead of creating extra variables, and you'd like to minimize the scope of all working variables. SolutionSample code folder: Chapter 08\ForEachLoops Use the For Each looping construct to process each element of an array. DiscussionThe following code creates a simple string array of fruit names, then processes each string in the array inside a For Each loop: Dim result As New System.Text.StringBuilder Dim fruitArray( ) As String = { _ "Oranges", "Apples", "Grapes", "Bananas", "Blueberries"} For Each fruit As String In fruitArray result.AppendLine(fruit) Next fruit MsgBox(result.ToString( )) The For Each line declares a temporary variable named fruit that exists only for the duration of the For Each loop. This ties the variable name closely to the processing going on locally and frees up resources as soon as that processing is completed. Also, there is no need to access the length of the array to control the looping because the loop implicitly processes all elements, no matter what the array's size is. (The standard For loop syntax requires a separate counting variable and access to the array's length.) Figure 8-14 shows the results displayed by the example code. Figure 8-14. Processing arrays with For Each loops |