C# GetEnumerator MethodUse the GetEnumerator method on the List type. Call MoveNext and access Current.
GetEnumerator. Some .NET collection types offer the GetEnumerator method. This method returns an Enumerator object that can be used to loop through the collection.
Complete knowledge of the actual collection type is not needed. We can use GetEnumerator in a while-loop, and call MoveNext on each iteration.
Example. This program shows how the GetEnumerator method on the List type works. On a List(int), GetEnumerator returns a List(int) Enumerator object.
Enumerator This object implements IEnumerator(int). We can then write methods that receive IEnumerator(int).
IEnumerator With GetEnumerator, it becomes possible to write methods that act on the IEnumerator interface.
Info IEnumerator is not the same as IEnumerable. It is an interface implemented by Enumerator objects.
using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(1); list.Add(5); list.Add(9); List<int>.Enumerator e = list.GetEnumerator(); Write(e); } static void Write(IEnumerator<int> e) { while (e.MoveNext()) { int value = e.Current; Console.WriteLine(value); } } }
1 5 9
Other collection types also provide GetEnumerator. For example, LinkedList returns LinkedList(int) Enumerator. This object too can be passed to the Write method in the example above.
Thus We only have to have one Write method to handle all generic enumerators that handle integers.
Summary. GetEnumerator is an instance method provided on many collection types. A unified method can be used to loop over the Enumerator returned by all these collections.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on 8/21/2021 (image).
© 2007-2022 sam allen.
see site info on the changelog.