I am a VB.Net developer, kind of newbie in C#, While looking in C# documentation I came through Iterators and Generators, could not fully understand the use, I there anyone who can explain (in vb perceptive; if possible)
Asked
Active
Viewed 2.4k times
22
-
1Iterators are most often used to traverse lists of different types. Iterators are called Enumerators in .net. Another question regarding iterators: http://stackoverflow.com/questions/1227283/why-do-we-need-iterators-in-c – jgauffin Sep 22 '10 at 09:53
-
The term “generator” is used in other languages- see https://stackoverflow.com/questions/38274727/c-sharp-generator-method – Michael Freidgeim Oct 06 '19 at 10:56
1 Answers
37
Iterators are an easy way to generate a sequence of items, without having to implement IEnumerable<T>
/IEnumerator<T>
yourself. An iterator is a method that returns an IEnumerable<T>
that you can enumerate in a foreach loop.
Here's a simple example:
public IEnumerable<string> GetNames()
{
yield return "Joe";
yield return "Jack";
yield return "Jane";
}
foreach(string name in GetNames())
{
Console.WriteLine(name);
}
Notice the yield return
statements: these statement don't actually return from the method, they just "push" the next element to whoever is reading the implementation.
When the compiler encounters an iterator block, it actually rewrites it to a state machine in a class that implements IEnumerable<T>
and IEnumerator<T>
. Each yield return
statement in the iterator corresponds to a state in that state machine.
See this article by Jon Skeet for more details on iterators.

mnme
- 620
- 6
- 19

Thomas Levesque
- 286,951
- 70
- 623
- 758
-
1It would be helpful to see an example of when you might need to do this. Your simple example here could just be replaced with an array of strings, if the goal is just to allow enumeration over "Joe" "Jack" and "Jane" ? – MarkJ Feb 16 '11 at 13:55
-
Yes, this example isn't very useful, you could easily use an array instead. For more useful examples, see [Jon Skeet's series on Reimplementing Linq to Objects](http://msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx) ;) – Thomas Levesque Feb 16 '11 at 14:54
-
In the interest of keeping this answer relative, Jon Skeet's series no longer exists at the above url. It can be found here: https://codeblog.jonskeet.uk/category/edulinq/ – John Kraft May 15 '18 at 19:52