Iterate IEnumerable <T>. The best way?

Looking at the implementation of the method

void InsertRange(int index, IEnumerable<T> collection) 

in the List <> class (.NET Framework 4.5.2), I see iteration over a collection like this

 using(IEnumerator<T> en = collection.GetEnumerator()) { while(en.MoveNext()) { Insert(index++, en.Current); } } 

I wonder what might cause the syntax of this syntax to be

 foreach(var item in collection) { Insert(index++, item) } 

I created an assembly with two methods, each of which uses a different approach. Then, looking at the generated IL code, I see both methods that call the Dispose method, implemented by the IEnumerator<T> implementation and, therefore, IDisposable .

So, IDisposable not the reason, and here is my question.

Is there any reason to prefer one syntax versus another besides simple style (ish)?

+7
c #
source share
4 answers

foreach is the recommended method because you do not provide details about how you want to iterate over the numbering. In addition, you write less code and read more.

+5
source share

They are exactly equivalent, it is something called syntactic sugar . The only reason to use foreach is that it is shorter, less error prone, more readable, etc.

You can copy the article in foreach on MSDN .

+3
source share

for loops faster than foreach. The difference is now tiny, so it’s usually not even worth considering. I think there was a bigger difference in earlier versions of .net.

0
source share

Any collection that inherits from IEnumerable<T> (an enumerated object) can be enumerated using a foreach loop.

Consider the following example:

 foreach(char c in "Ehsan") { Console.WriteLine(c); } 

This is the basic way to repeat an IEnumerable<T> iteration if the enumerator implements the iDisposable foreach using the using statement and it will implilctly position the enumerator object.

At a low level, we can read it:

 using(var enumerator = "Ehsan".GetEnumerator()) { while(enumerator.MoveNext()) { var element = enumerator.Current; Console.WriteLine(element); } } 

So, foreach does your work, you don’t need to write as above to enumerate IEnumeable<T>

0
source share

All Articles