2

What is the difference between creating Enumerable or Enumerator using Iterators in C#? I know that Iterators are used to create a private class that implements Enumerable or Enumerator...

Which way is better to create an enumerable type?

Wasif Hossain
  • 3,900
  • 1
  • 18
  • 20
Csharper
  • 27
  • 5
  • You're probably referring to iterator blocks. You should read this: http://csharpindepth.com/articles/chapter6/iteratorblockimplementation.aspx – Henrik Feb 24 '14 at 11:20

1 Answers1

4

Every type that implements the IEnumerable interface should implement a method GetEnumerator which returns a type that implements the IEnumerator interface. Then having an enumerator you can use the foreach statement, which in its essence implements the iterator pattern, to traverse the elements of a collection of your custom type.

For further clarification please take a look to the following links:

  1. IEnumerable
  2. IEnumerator
  3. Iterator Pattern

So in order to answer to your question, I have to say that we shouldn't try to compare the IEnumerable and IEnumerator. They both are used together, when we want to use the iterator pattern for a custom type.

Hejazi
  • 16,587
  • 9
  • 52
  • 67
Christos
  • 53,228
  • 8
  • 76
  • 108