i am quite confused about the differences between the various types in the C# language. specifically
- IEnumerable
- IEnumerator
i am quite confused about the differences between the various types in the C# language. specifically
IEnumerable<T>
represents a sequence which can be enumerated - such as a list.
IEnuerator<T>
effectively represents a cursor within a sequence.
So imagine you have a sequence - you can iterate over that with several "cursors" at the same time. For example:
List<string> names = new List<string> { "First", "Second", "Third" };
foreach (string x in names)
{
foreach(string y in names)
{
Console.WriteLine("{0} {1}");
}
}
Here, List<string>
implements IEnumerable<string>
, and the foreach
loops each call GetEnumerator()
to retrieve an IEnumerator<string>
. So when we're in the middle of the inner loop, there are two independent cursors iterating over a single sequence.
IEnumerable
a collection that can be enumerated.
IEnumerator
the thing that actually manages location through the collection, provides access to the current item and allows you to move on to the next.
So one would use an IEnumerator
to walk through an IEnumerable
.