Information Technology Reference
In-Depth Information
The foreach Statement
The foreach statement allows you to sequentially access each element in an array. It is actually
a more general construct in that it also works with other collection types—but this section will
only discuss its use with arrays. Chapter 20 will cover its use with other collection types.
The important points of the foreach statement are the following:
￿The iteration variable is a temporary, read-only variable of the same type as the ele-
ments of the array. The foreach statement uses the iteration variable to sequentially
represent each element in the array.
￿The syntax of the foreach statement is where
- Type is the type of the elements of the array.
- Identifier is the name of the iteration variable .
- ArrayName is the name of the array to be processed.
- Statement is a simple statement or a block that is executed once for each element in
the array.
Iteration variable declaration
foreach( Type Identifier in ArrayName )
Statement
The way the foreach statement works is the following:
￿
It starts with the first element of the array and assigns that value to the iteration variable .
￿
It then executes the body of the statement. Inside the body, you can use the iteration
variable as a read-only alias for the array element.
After the body is executed, the foreach statement selects the next element in the array
and repeats the process.
￿
In this way, it cycles through the array, allowing you to access each element one by one.
For example, the following code shows the use of a foreach statement with a one-dimensional
array of four integers:
￿The WriteLine statement, which is the body of the foreach statement, is executed once
for each of the elements of the array.
The first time through the loop, iteration variable item has the value of the first element
of the array. Each successive time, it will have the value of the next element in the array.
￿
int[] arr1 = {10, 11, 12, 13};
Iteration variable declaration
Iteration variable use
foreach( int item in arr1 )
Console.WriteLine("Item Value: {0}", item);
Search WWH ::




Custom Search