Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating an IEnumerable<T>. Best way? [closed]

Tags:

c#

Looking to the implementation of the method

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

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

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

I am wondering what could be the reason to prefer that syntax over this one

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

I have created an assembly with two methods each one using a different approach. Then, looking into the generated IL code, I can see both methods calling the Dispose method enforced by the implementation of the IEnumerator<T> and hence IDisposable.

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

Is there any reason to prefer one syntax vs the other, other than simple style(ish) preferences?

like image 694
Juan M. Elosegui Avatar asked Jul 20 '15 16:07

Juan M. Elosegui


2 Answers

foreach is the recommended way because you don't specify details about how you want to iterate over the enumeration. Also, you write less code and it's more readable.

like image 115
Francisco Goldenstein Avatar answered Nov 15 '22 10:11

Francisco Goldenstein


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

You can chceck the article on foreach implementation on MSDN.

like image 21
w.b Avatar answered Nov 15 '22 10:11

w.b