July 2001
Intermediate to advanced
688 pages
16h 14m
English
The
foreach looping
statement is new to the C family of languages, though it is 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 in expression) 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;
private int size;
}
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+10);
}
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:
for (int i = 0; i < empArray.Length; i++) { Console.WriteLine(empArray[i].ToString()); } ...Read now
Unlock full access