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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With