The foreach loop

Learning Resources
 

The foreach loop


Foreach is a loop construct. It has very simple syntax. It does not use an integer index. Instead, it is used on a collection and returns each element in order. This is called enumeration. It eliminates errors caused by incorrect index handling.

Example
This example shows how you can use the keyword foreach on a string array to loop through the elements in the array.

In the foreach-statement, you do not need to specify the loop bounds minimum or maximum, and do not need an 'i' variable as in for-loops.

Note: This results in fewer characters to type and code that it is easier to review and verify, with no functionality loss.

using System;

class Program
{
    static void Main()
    {
    // Use a string array to loop over.
    string[] ferns =
    {
        "Psilotopsida",
        "Equisetopsida",
        "Marattiopsida",
        "Polypodiopsida"
    };
    // Loop with the foreach keyword.
    foreach (string value in ferns)
    {
        Console.WriteLine(value);
    }
    }
}

Output

Psilotopsida
Equisetopsida
Marattiopsida
Polypodiopsida

Note - The foreach-statement contains the reserved "foreach" keyword followed by a parenthetical containing the declaration of the iteration variable. The iteration variable "string value" can be a different type such as "int number" if you are looping over that type.

 

 For Support