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 in expression) statement

Thus, you might update Example 9-1 to replace the for statements that iterate over the contents of the populated array with foreach statements, as shown in Example 9-2.

Example 9-2. Using foreach

using System;
using System.Collections.Generic;
using System.Text;

namespace UsingForEach
{
    // 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. In Example 9-1, you created a for statement that measured the size of the array and used a temporary counting variable as an index into the array, as in the following:

for (int ...

Get Programming C# 3.0, 5th 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.