using System; using System.Collections; public class Example : IEnumerator, IDisposable { private int[] _items = { 1, 2, 3, 4, 5 }; private int _index = -1; public bool MoveNext() { if (_index < _items.Length - 1) { _index++; return true; } else return false; } public void Reset() { _index = -1; } public object Current { get { return _items[_index]; } } public void Dispose() { Console.WriteLine("Disposed"); } } class MainClass { static void Main() { using (var e = new Example()) { while (e.MoveNext()) { Console.WriteLine(e.Current); } } } }
using System; using System.Collections.Generic; class MainClass { static void Main() { ListIn this example, we use the GetEnumerator method of the List class to create an enumerator for the collection. We use a using statement to ensure that the Dispose method is called after the enumerator is used. Package/Library: System.Collections.Genericnumbers = new List { 1, 2, 3, 4, 5 }; using (var e = numbers.GetEnumerator()) { while (e.MoveNext()) { Console.WriteLine(e.Current); } } } }