foreach on Collection, List, IList, ICollection, ...

  • Thread starter Thread starter Dansk
  • Start date Start date
D

Dansk

Hi all,

Can I assume that when I loop throw a Collection, List, IList,
ICollection, ... by using foreach, I first get the element of index 0,
then index 2, and so on until the last one ?

Thanks for your answers,

Dansk.
 
Actually, I would say that you can't depend on them starting at index 0 in a
foreach. The reason being that these are all interfaces and thus can be
implemented any way the programmer wants and you may have some developer
that for some odd reason likes to start at index 1. However in order for you
to use foreach on a collection that collection has to implement the
IEnumerator interface so I think you can be pretty sure that even if it
doesn't start at index 0 you will still hit each element in the collection.

If you are really that concerned about it starting at 0 then I would suggest
using a for loop instead.
 
Jeremy Shovan said:
Actually, I would say that you can't depend on them starting at index 0 in a
foreach. The reason being that these are all interfaces and thus can be
implemented any way the programmer wants and you may have some developer
that for some odd reason likes to start at index 1. However in order for you
to use foreach on a collection that collection has to implement the
IEnumerator interface so I think you can be pretty sure that even if it
doesn't start at index 0 you will still hit each element in the collection.

If you are really that concerned about it starting at 0 then I would suggest
using a for loop instead.

Alternatively, consult the documentation for whatever collection you're
looking at. For instance, the documentation for List<T> makes it fairly
clear that you'll get the results in the natural order.

I can't remember ever being in a situation where a collection *had* a
natural order but didn't return the elements in that order from the
iterator. The benefits to readability of using foreach outweigh the
conservatism in this case, IMO.
 
Dansk said:
Hi all,

Can I assume that when I loop throw a Collection, List, IList,
ICollection, ... by using foreach, I first get the element of index 0,
then index 2, and so on until the last one ?

Thanks for your answers,

Dansk.

Yes, you can expect this. This is an elementary requirement of the enumerator functionality.

--
Try Code-Navigator on http://www.codenav.com
a source code navigating, analysis and developing tool.
It supports following languages:
* C/C++
* Java
* .NET (including CSharp, VB.Net and other .NET components)
* Classic Visual Basic
* PHP, HTML, XML, ASP, CSS
* Tcl/Tk,
* Perl
* Python
* SQL,
* m4 Preprocessor
* Cobol
 
Back
Top