retrieve arraylist items using enumerators

ArrayList allows us to use Enumerators to access the collection elements. This is possible because the ArrayList class implements IEnumerable interface. The GetEnumerator method of IEnumerable interface returns Enumerator object for the entire ArrayList. Using Enumerators, we can read the data in the collection, but we cannot modify the underlying collection.



At the beginning, the enumerator is positioned before the first element in the collection and to access the first element, we have to use MoveNext() method to advance and read the value of the first element. When the enumerator is positioned after the last element in the collection, the MoveNext method returns false and the While Loop exits.

private void Form1_Load(object sender, EventArgs e)
{
	ArrayList arrayList = new ArrayList();
	arrayList.Add("Customer1");
	arrayList.Add("Customer2");
	arrayList.Add("Customer3");
	arrayList.Add("Customer4");
	arrayList.Add("Customer5");
	
    //Iterating through items - Using Enumerators
	IEnumerator enumerator = arrayList.GetEnumerator();
	while (enumerator.MoveNext())
	{
		str += enumerator.Current.ToString() + "\n";
	}
	MessageBox.Show(str);