Traversing an Entire Array with the foreach Statement

Instead of using the for loop to traverse an entire array, you can apply C#'s foreach statement as a convenient alternative. For example, to print every array element value of the array childbirths declared and defined as

uint [] childbirths =  { 1340, 3240, 1003, 4987, 3877} ;

you can write the following foreach statement:

foreach (uint temp in childbirths)
{
      Console.WriteLine(temp);
}

to provide the following output:

					1340
3240
1003
4987
3877

This deserves a closer look. The foreach statement consists of a header and a loop body (see Figure 10.4). The loop body can either be a single statement or a compound statement. The first two words inside the parentheses of the header must consist ...

Get C# Primer Plus 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.