
15 Statements
15.8 Iteration statements
15.8.4 The foreach statement
Paragraph 11 The foreach statement enumerates the elements of a collection, executing an embedded statement for each element of the collection. foreach-statement : foreach ( type identifier in expression ) embedded-statement
Paragraph 21 The type and identifier of a foreach statement declare the iteration variable of the statement. 2 The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement. 3 During execution of a foreach statement, the iteration variable represents the collection element for which an iteration is currently being performed. 4 A compile-time error occurs if the embedded statement attempts to modify the iteration variable (via assignment or the ++ and --operators) or pass the iteration variable as a ref or out parameter.
Paragraph 31 The type of the expression of a foreach statement must be a collection type (as defined below), and an explicit conversion (§13.2) must exist from the element type of the collection to the type of the iteration variable. 2 If expression has the value null, a System.NullReferenceException is thrown.
Paragraph 41 A type C is said to be a collection type if it implements the System.IEnumerable interface or implements the collection pattern by meeting all of the following criteria: foreach (ElementType element in collection) statementcorresponds to one of two possible expansions:
Enumerator enumerator = (collection).GetEnumerator();
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
}
IEnumerator enumerator =
((System.IEnumerable)(collection)).GetEnumerator();
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
}
using System;
class Test
{
static void Main() {
double[,] values = {
{1.2, 2.3, 3.4, 4.5},
{5.6, 6.7, 7.8, 8.9}
};
foreach (double elementValue in values)
Console.Write("{0} ", elementValue);
Console.WriteLine();
}
}
The output produced is as follows: 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9end example]
| |
| Jagger Software Ltd | |
| Company # 4070126 | |
| VAT # 762 5213 42 |