Anthony Bouch <an*****@nospamforever.com> wrote:
Everything I know about looping structures says to be careful about
expressions that need to be evaluated again and again for each
test/increment of a loop.
I came across this piece of code the other day and stopped to think for a
minute about whether it was right or not.
foreach (XmlNode node in doc.SelectNodes("/root/map/");)
{
//Do something
}
Am I missing something here or is this going to perform the Xpath select for
every iteration? Or is it the case that once the iterator has been retrieved
by the foreach statement that it will use the same one for each loop without
evaluating the SelectNodes statement over and over again.
Exactly. If it were re-executing SelectNodes each time, you'd keep
getting the first element of the list :)
If I was able to read IL - I would look at what was going on here myself.
Fortunately there's the C# spec to go on as well :)
From the ECMA spec, section 15.8.4:
<quote>
A foreach statement of the form:
foreach (ElementType element in collection) statement
corresponds to one of two possible expansions:
If the collection expression is of a type that implements the
collection pattern (as defined above), the expansion of the foreach
statement is:
<snip - this isn't the normal case>
Otherwise; the collection expression is of a type that implements
System.IEnumerable, and the expansion of the foreach statement is:
IEnumerator enumerator =
((System.IEnumerable)(collection)).GetEnumerator() ;
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
}
</quote>
Note that the "collection" expression is only evaluated once.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too