views:

2089

answers:

6

Hello,

I want to implement the iterator pattern in VB.net, which does not have the yield keyword.

Any ideas or links please?

+1  A: 

Hmm, looks like you might be out of luck:

I was struggling with an issue today when converting some C# to VB.NET. C# has a really cool "yield return" statement that is used in an iterator block to provide a value to the enumerator object. VB.NET does not have the "yield" keyword. So, there are a few solutions (none of which are really clean) to get around this. You could use a return statement to return the value if you are looping through and would like to break an enumerator and return a single value. However, if you'd like to return the entire enumeration, create a List() of the child type and return the list. Since you are usually using this with an IEnumerable, the List() will work nice.

That was written a year ago, not sure if anyone has come up with anything else better since then..

Jeff Atwood
Hehe, look at this link paying attention to the orange color note below: http://www.vbdotnetheaven.com/UploadFile/rmcochran/yieldreturn11142006235137PM/yieldreturn.aspx
splattne
+2  A: 

VB.net does not support the creation of custom iterators and thus has no equivalent to the C# yield keyword. However you might want to look at this KB article for more information.

Jasper Bekkers
+1  A: 

C#'s yield keyword forces the compiler to create a state machine in the background to support it. VB.Net does not have the yield keyword. But it does have a construct that would allow you to create a state machine within a function: Static function members.

It should be possible to mimic the effects of a yield return function by creating a generic class that implements IEnumerable as well as the needed state machine and placing an instance as a static member inside your function.

This would, of course, require implementing the class outside of the function. But if done properly the class should be re-usable in the general case. I haven't played with the idea enough to provide any implementation details, though.

Joel Coehoorn
Hey Joel, you have mentioned this idea at least twice now. Fancy fleshing out your idea further?
Harry
I have looked into this a little deeper, and I'm no longer sure you can create the same kind of state machine as C#'s yield keyword in a VB.Net Static local variable. Not that it would be impossible, but it certainly wouldn't be trivial and in the end you'd still have to write some odd code assign to the machine. Even that you couldn't do in visual studio 2005, as it would require lambda expressions.
Joel Coehoorn
+4  A: 

Still getting my head around this concept also.

The article 'Use Iterators in VB Now' was recently published in Visual Studio Magazine.

http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2972

+1  A: 

Just implement the IEnumerator and IEnumerable interfaces. This is perfectly explained here

+2  A: 

I think is better explained here