On Wed, 19 Apr 2006 09:54:02 -0700, kh <kh@newsgroups.nospam> wrote:
I notice that using iterators it is possible to modify a collection whilst
enumerating over it's elements.
C# 2.0 iterators provide a code transformation, via a generated state
machine, that turns yield return statements into reentry points for
subsequent calls to MoveNext() on the generated IEnumerator
implementation. This code transformation is useful for things which
aren't 'collections' per se: for example, an infinite stream of
positive integers, or an infinite stream of random numbers.
Is this by design or just a side-effect of
their implementation? Viewing the disassembly for the generated classes I
note that the compiler-generated enumerator has no version checking. Is there
an in-depth analysis of this on the www anywhere?
Iterators are useful for more than simply implementing collection
classes, or otherwise they wouldn't be a useful addition to the
language.
Who spends all their time implementing collection classes? If enough
people did this to warrant the feature, then somebody in the BCL
development team isn't doing their job.
Thus, it's a language feature with a far wider range of applicability.
Personally, whenever I need a collection, I descend from an existing
collection class like Collection<T>. However, I've implemented many
iterators, none of which were over an actual collection, but rather
aggregated data from other places, or synthesised data from some
algorithm.
If the C# 2.0 iterator implementation kept track of some notion of
read-only-ness (and that's not possible anyway, since it doesn't know
where I'm getting the data), I wouldn't be using it at all.
-- Barry