X hits on this document

905 views

0 shares

0 downloads

0 comments

189 / 396

C# LANGUAGE SPECIFICATION

an array is as follows: For single-dimensional arrays, elements are traversed in increasing index order, starting with index 0 and ending with index Length  1. For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left.

A foreach statement of the form:

foreach (ElementType element in collection) statement

corresponds to one of two possible expansions:

If the collection expression is of a type that implements the collection pattern (as defined above), the expansion of the foreach statement is:

E 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(); }

Significant optimizations of the above are often easily available. If the type E implements System.IDisposable, then the expression (enumerator as System.IDisposable) will always be non-null and the implementation can safely substitute a simple conversion for a possibly more expensive type test. Conversely, if the type E is sealed and does not implement System.IDisposable, then the expression (enumerator as System.IDisposable) will always evaluate to null. In this case, the implementation can safely optimize away the entire finally clause.

Otherwise, the collection expression is of a type that implements System.IEnumerable, and the expansion of the foreach statement is:

IEnumerator enumerator =           ((System.Collections.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(); }

In either expansion, the enumerator variable is a temporary variable that is inaccessible in, and invisible to, the embedded statement, and the element variable is read-only in the embedded statement.

The following example prints out each value in a two-dimensional array, in element order:

using System;

176Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views905
Page views905
Page last viewedTue Dec 06 20:37:11 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments