C Sharp

The foreach Statement

For years, languages such as Visual Basic have had a special statement specifically designed for the iteration of arrays and collections. C# also has such a construct, the foreach statement, which takes the following form: -

    foreach (type in expression)
    embedded-statement

Take a look at the following array class: -

class MyArray
{
    public ArrayList words;
    public MyArray()
    {
        words = new ArrayList();
        words.Add("foo");
        words.Add("bar");
        words.Add("baz");
    }
}

From the different iteration statements you've already seen, you know that this array can be traversed using any of several different statements. However, to most Java and C++ programmers, the most logical way to write this application would be like this: -

using System;
using System.Collections;
class MyArray
{
    public ArrayList words;
    public MyArray()
    {
        words = new ArrayList();
        words.Add("foo");
        words.Add("bar");
        words.Add("baz");
    }
}
class Foreach1App
{
    public static void Main()
    {
        MyArray myArray = new MyArray();
        for (int i = 0; i < myArray.words.Count; i++)
        {
            Console.WriteLine("{0}", myArray.words[i]);
        }
    }
}

But this approach is fraught with potential problems: -

  • If the for statement's initializationvariable (i) isn't initialized properly, the entire list won't be iterated.
  • If the for statement's Boolean expressionisn't correct, the entire list won't be iterated.
  • If the for statement's step isn't correct, the entire list won't be iterated.
  • Collections and arrays have different methods and properties for accessing their count.
  • Collections and arrays have different semantics for extracting a specific element.
  • The for loop's embedded statement needs to extract the element into a variable of the correct type.

The code can go wrong many ways. Using the foreach statement, you can avoid these problems and iterate through any collection or array in a uniform manner. With the foreach statement, the previous code would be rewritten as follows: -

using System;
using System.Collections;
class MyArray
{
    public ArrayList words;
    public MyArray()
    {
        words = new ArrayList();
        words.Add("foo");
        words.Add("bar");
        words.Add("baz");
    }
}
class Foreach2App
{
    public static void Main()
    {
        MyArray myArray = new MyArray();
        foreach (string word in myArray.words)
        {
            Console.WriteLine("{0}", word);
        }
    }
}

Notice how much more intuitive using the foreach statement is. You're guaranteed to get every element because you don't have to manually set up the loop and request the count, and the statement automatically places the element in a variable that you name. You need only refer to your variable in the embedded statement.