1

Possible Duplicate:
Can anyone explain IEnumerable and IEnumerator to me?
What is the difference between IEnumerator and IEnumerable?

We can implement IEnumerator or its generic version and thus use it directly.

So why do we require IEnumerable? Do we require IEnumerable to give a new set of data or is it something else!

Community
  • 1
  • 1
Anirudha
  • 32,393
  • 7
  • 68
  • 89

2 Answers2

4

IEnumerable specifies an aspect of a class: it tells you that can be enumerated. IEnumerator is implemented by classes that perform the actual job of providing results during the enumeration. These are two different things.

Putting it another way:

  • We need IEnumerable as a way to say "this class contains enumerable data"
  • We need IEnumerator so that after we determine that an object can be enumerated, we can tell it "start giving me the data in that object one by one"
Jon
  • 428,835
  • 81
  • 738
  • 806
  • thanks..but is it that ienuerable is used becuz it gives a new set of data so that multiple classes can acces that data individually – Anirudha Jan 09 '12 at 14:56
  • @Anirudha: `IEnumerable` just tells you that you can get an `IEnumerator` out of an object. The `IEnumerator` is what allows you to actually enumerate. – Jon Jan 09 '12 at 14:57
0

You can implement IEnumerator without IEnumerable. Implementing an IEnumerable requires implementing an IEnumerator, but not the opposite.

With IEnumerable you can get the nice syntax candy of foreach.

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
  • thts right but y do we require ienumerable when the same thing can be done wid ienumerator – Anirudha Jan 09 '12 at 14:46
  • @Anirudha Where to get the enumerator for a given collection? Call its `GetEnumerator()` method. How do we know the collection has such a method? Because the collection implements IEnumerable. – phoog Jan 09 '12 at 15:10