tags:

views:

83

answers:

2

i am quite confused about the differences between the various types in the C# language. specifically

  • IEnumerable
  • IEnumerator
+10  A: 

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.

Jon Skeet
+1  A: 

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.

Paul Ruane