Share via


Array.GetEnumerator Method

Gets an IEnumerator object for a specified array.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax

 public virtual IEnumerator GetEnumerator ()

Return Value

An IEnumerator object for the specified Array.

Remarks

Enumerators facilitate the reading of data in a collection; you cannot use enumerators to modify the underlying collection.

Initially, an enumerator is positioned before the first object in the specified collection. Calling the IEnumerator.Reset method also brings the enumerator back to this position. From this position, calling the IEnumerator.Current property throws an exception. Therefore, you must call the IEnumerator.MoveNext method to advance the enumerator to the first object in the collection before you can read the value of the IEnumerator.Current property.

The Current property returns the same object until either the MoveNext method or the Reset method is called. The MoveNext method sets the Current property to the next element.

After the end of the collection is passed, the enumerator is positioned after the last object in the collection, and calling MoveNext returns false. If the last call to MoveNext returned false, calling Current throws an exception. To set Current to the first object in the collection again, you can call Reset followed by MoveNext.

An enumerator remains valid as long as the collection you are using it in remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException exception. If the collection is modified between the invoking of MoveNext and the invoking of Current, Current returns the element that it is set to, even if the enumerator is already invalidated.

Note also that an enumerator does not have exclusive access to a collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify it, thus causing the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection for the duration of the enumeration or catch the exceptions that result from changes made by other threads.

Version Information

Available in .NET Micro Framework version 2.0, 2.5

See Also

Reference

Array Class
Array Members
System Namespace