7

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?

Juan M. Elosegui
  • 6,471
  • 5
  • 35
  • 48

4 Answers4

5

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.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Francisco Goldenstein
  • 13,299
  • 7
  • 58
  • 74
3

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.

w.b
  • 11,026
  • 5
  • 30
  • 49
0

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

Peter Dongan
  • 1,762
  • 12
  • 17
0

Any collection which inherits from IEnumerable<T> (an enumerable object) it can be enumerated using foreach loop.

Consider this example:

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

It is bascially a high level way of iterating the IEnumerable<T> , if the enumerator implements iDisposable the foreach statement uses using statement and it implilctly will dispose the enumerator object.

At low level we can wrtie it :

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

}

So the foreach is doing the work for you, you don't have to write like the above to enumerate the IEnumeable<T>

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160