Nostromo
Nostromo

Reputation: 1264

How to overload an iterator function without losing the advantages of the iterator

Since I usually use VB.net as my language of choice I didn't cope with yielding yet. Now I read, that they introduced yielding to VB.net as well, so I tried to learn about it, and now I have a question.

Let's say I have an Iterator function that uses yielding. For the sake of this question I created this rather useless function:

Public Iterator Function Test(ByVal gap As Integer) As IEnumerable(Of Integer)
    Dim running As Integer

    Do While running < (Integer.MaxValue - gap)
        Yield running
        running += gap
    Loop
End Function

If I understood yielding correctly, than the code stops after the yielding and only continues, when the next item is asked for.

So, in my example... if getting the next value for the running variable would need 1 second, then my code would only run 1 second if I only need the first number and it would run 5 seconds if I'd need 5 numbers.

So far, so good, but now I want to overload my function:

Public Function Test() As IEnumerable(Of Integer)
    Return Test(1)
End Function

It's not an Iterator function anymore, so did I lose the advantage of only needing as much time as I need numbers?

Upvotes: 1

Views: 219

Answers (1)

svick
svick

Reputation: 244968

It's not an Iterator function anymore, so did I lose the advantage of only needing as much time as I need numbers?

You did not. Iterator functions are not magic, all they do is give you a convenient way of implementing the IEnumerable(Of T) interface. So, to get the advantage of producing only the values you require, all you need is a method that returns a good implementation of that interface. And that could be any of:

  • An iterator method, like your Test(ByVal gap As Integer).
  • A method that calls an iterator method and returns the object it produces, like your Test().
  • A method that returns an instance of a type that implements the IEnumerable(Of T) interface by hand.

Upvotes: 2

Related Questions