views:

59

answers:

2

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)

+2  A: 

Unfortunately there's no yield equivalent in VB.NET. There's a nice article about emulating it.

Darin Dimitrov
The question is not about doing it in VB...
Thomas Levesque
+1  A: 

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.

Thomas Levesque