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