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
You can update Example
10-1 to replace the final two for
statements (that iterate over the contents
of the populated array) with foreach
statements, as shown in Example
10-2.
Example 10-2. Using foreach
foreach ( int i in intArray ) { Console.WriteLine( i.ToString( ) ); } foreach ( Employee e in empArray ) { Console.WriteLine( e.ToString( ) ); }
The output will be identical.