The foreach Statement
The
foreach
looping
statement is new to the C family of languages, though it is already
well known to VB programmers. The foreach
statement allows you to iterate through all the items in an array or
other collection, examining each item in turn. The syntax for the
foreach
statement is:
foreach (type
identifier
inexpression
)statement
Thus, you might update Example 9-1 to replace the
for
statements that iterate over the contents of
the array with foreach
statements, as shown in
Example 9-2.
Example 9-2. Using foreach
namespace Programming_CSharp { using System; // a simple class to store in the array public class Employee { // a simple class to store in the array public Employee(int empID) { this.empID = empID; } public override string ToString( ) { return empID.ToString( ); } private int empID; } public class Tester { static void Main( ) { int[] intArray; Employee[] empArray; intArray = new int[5]; empArray = new Employee[3]; // populate the array for (int i = 0;i<empArray.Length;i++) { empArray[i] = new Employee(i+5); } foreach (int i in intArray) { Console.WriteLine(i.ToString( )); } foreach (Employee e in empArray) { Console.WriteLine(e.ToString( )); } } } }
The output for Example 9-2 is identical to Example 9-1. However, rather than creating a
for
statement that measures the size of the array
and uses a temporary counting variable as an index into the array as
in the following, we try another approach:
for (int i = 0; i < empArray.Length; i++) { Console.WriteLine(empArray[i].ToString( ...
Get Programming C#, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.