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)?
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.
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 .
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.
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>