Hello, I'm converting some C# code and I'm stuck at this line:
c# Code:
while (iterator.MoveNext()) yield return iterator.Current;
The function returns IEnumerable. Can anyone tell me how this fragment can be re-written in VB?
Printable View
Hello, I'm converting some C# code and I'm stuck at this line:
c# Code:
while (iterator.MoveNext()) yield return iterator.Current;
The function returns IEnumerable. Can anyone tell me how this fragment can be re-written in VB?
I know that VB doesn't have an equivalent to the C# 'yield' keyword. I didn't know what the best way to approximate it was though. I Googled. I found the answer. Funny that.
http://blog.matthewdoig.com/?p=81
Well then I read this article. But still I'm not quite sure I understand how this works.
Here's the original function in c#:
c# Code:
public static IEnumerable ForwardNodeIterator(Node firstNode, bool mustBeVisible) { ForwardNodeEnumerator iterator = new ForwardNodeEnumerator(firstNode, mustBeVisible); while (iterator.MoveNext()) yield return iterator.Current; }
I have a class that implements IEnumerator(Of node) (as in the original and it does not implement IEnumerable. Does the article you provided suggest that I need also a helper class that implements IEnumerable(Of Node) in order to achieve the result?
P.S.
I have a class that implements IEnumerator
If add this to the class:
vb Code:
Implements IEnumerator(Of Node) ' IEnumerator implementation here Implements IEnumerable(Of Node) Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of Node) Implements System.Collections.Generic.IEnumerable(Of Node).GetEnumerator Return Me End Function Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Me End Function
would this work?
I haven't actually read the details but I do know that you need to do a reasonable amount of work to simulate 'yield' in VB.
You "simply" have to implement IEnumerable and IEnumerator interfaces. It's not pretty though. The yield keyword in C# basically writes a state machine for you that does the implementation of those two interfaces. I'd suggest that it's probably not worth the effort. If you really need to yield (rather than creating the entire sequence and returning everything in a List or array or similar) then I'd suggest it would be easiest to not convert that code from C#.
Supposedly, VB will be getting an equivalent to yield in a future version that will actually be more powerful than the simple yield keyword in C#.