Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach while adding items to the looping collection

Tags:

c#

.net

This is the situation:

I'm browsing through some code and I wondered if the following statement takes a reference of the selected collection or a copy with which it replaces the original object when the foreach loop finishes. If the first, will it take the new found pages and join them in the loop?

foreach(Page page in Pages)
{
    page.AddRange(RetrieveSubPages(page.Id));
}

Edit: I'm sorry, I made a typo.

It should be this:

foreach(Page page in pages)
{
    pages.AddRange(RetrieveSubPages(page.Id));
}

What i tried to say is that if i add some objects to the enumerating collection, will it join those objects in the foreach?

like image 428
Rickjaah Avatar asked Jul 09 '26 12:07

Rickjaah


1 Answers

It looks like the code doesn't modify the Pages collection, but the content of the objects in the Page objects in the Pages collection. The Page type having at least collection like method.

In general each collection implements iteration in a way suitable for itself, and generally becomes unmodifiable while iterating, but one could implelment a collection which iterates by taking a snapshot of itself.

There is no mechanism to detect exit from a loop which would allow action to be taken at that point (consider how this would interact with exceptions, break and return in the body of the loop).

like image 106
Richard Avatar answered Jul 12 '26 00:07

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!