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 = ....
}
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 = ....
}
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.
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.
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 yourfor
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).