Wednesday, December 13, 2006

foreach Considered Wack Quite Often

{

Don't get me wrong, it's not a jihad I have against the foreach in C#, it's just the fact that if I had a nickel (okay, a quarter to be realistic) for each time I changed a foreach to a normal for loop because I needed to track my position as I iterated through a collection and no underlying index was provided, I'd have enough money for coffee each week.

A simple example from the .NET world is the DataTable; when you iterate the Rows collection, the Rows don't expose an index. After seduction for the easy foreach, I end up with:

for(int i=0;i<myTable.Rows.Count;i++){}

There's only one time that a normal for loop got the better of me - I had to iterate and remove items from the collection. Modifying a collection that you're going through causes trouble but it's easily remedied - not with recursion as some would have it, but by simply going backward:

for(int i=myTable.Rows.Count -1;i>-1;i--){}

Besides its syntactic elegance, of what benefit is the foreach? By calling the underlying enumerator?

}

No comments: