ArrayList.GetEnumerator Method is used to get an enumerator for the entire ArrayList.
Syntax:
public virtual System.Collections.IEnumerator GetEnumerator ();
Return Value: It returns an IEnumerator for the entire ArrayList.
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList myList = new ArrayList();
myList.Add( "Geeks" );
myList.Add( "GFG" );
myList.Add( "C#" );
myList.Add( "Tutorials" );
IEnumerator enumerator = myList.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}
|
Output:
Geeks
GFG
C#
Tutorials
Example 2:
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList myList = new ArrayList();
myList.Add(14);
myList.Add(45);
myList.Add(78);
myList.Add(57);
IEnumerator enumerator = myList.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}
|
Note:
- The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator.
- Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
- Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element.
- An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
- This method is an O(1) operation.
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
02 Jul, 2019
Like Article
Save Article