Length of Yield Return

2.9k views Asked by At

Is there a way to get the number of yield returns from within a function without keeping a counter variable? For instance?

  IEnumerable<someobject> function
  {
      for loop
          yield return something

      int numberreturned = ....
  }
4

There are 4 answers

0
Frédéric Hamidi On BEST ANSWER

That would defeat the purpose of yield return.

Using yield return means you want to implement a generator (MSDN calls that an iterator block), i.e. an object that computes every value it returns on the fly. By definition, generators are potentially infinite, and therefore control might never leave your for loop.

Streams work the same way. To compute the length of a stream, you have to exhaust it, and you might never return from doing that. After all, the data could come from an infinite source (e.g. /dev/zero).

1
Bala R On

you could use the extension method count on the the IEnumerable<> that your function returns

function().Count()
1
Reddog On

You could use the IEnumerable.Count extension method!

I think that yield return is intended for the compiler to implicitly build a basic iterator using the statement that follows it.

If you want a more complex iterator then you might implement that in a more explicit manner.

0
AudioBubble On

No. This is not possible without a counter -- there is no way to access the returned stream from within the function itself. (If it were possible, I wonder what sort of strange semantics/quirks it would entail?)

However, this is perfectly okay (if questionable) with a counter, even if the question does not desire such a response ;-) Remember that this form of construct is "magic" around closures invoked when the next item in the stream (iterator) is required -- that is, flow control leaves and re-enters at the yield return as required.

IEnumerable<someobject> Function
{
  int counter = 0;
  foreach (...) {
      counter++;
      yield return ...;
  }
  // after here we know count -- /assuming/ control gets here
  // 1) value can't be 'normally returned'
  // 2) and if the stream evaluation never exhausts the loop above
  //    then flow-control will never get here
}

Happy coding.