views:

6179

answers:

4

What are the differences between IEnumerator and IEnumerable?

+13  A: 

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement.

Definition

IEnumerable 

public IEnumerator GetEnumerator();

IEnumerator

public object Current;
public void Reset();
public bool MoveNext();

example code from codebetter.com

cgreeno
BtBh, your code doesn't make any sense. IEnumerable defines a method which returns an IEnumerable? And you are saying IEnumerable has GetEnumerator, and then IEnumerable also has Current, Reset and MoveNext. That is not correct...
Rex M
@Rex M: I think the code does make sense. IEnumerable has a method GetEnumerator which returns an IEnumer*ator*, not IEnumer*able*.
Lernkurve
@Lernkurve the answer was modified to be correct after I posted my comment.
Rex M
+2  A: 

An IEnumerator is a thing that can enumerate: it has the MoveNext, Current, and Reset methods (which in .NET code you probably won't call explicitly, though you could).

An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator.

Which do you use? The only reason to use IEnumerator is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator. But you'd still need to return that IEnumerator in an IEnumerable class.

For a look at what an enumerator (implementing IEnumerator<T>) looks like, see any Enumerator<T> class, such as the ones contained in List<T>, Queue<T>, or Stack<T>. For a look at a class implementing IEnumerable, see any standard collection class.

Kyralessa
+1  A: 

An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is a a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

An Enumerable is a class that can give you Enumerators. It has a method called GetEnumerator which gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

SLaks