We had some code here (in VS2005 and C#2.0) where the previous engineers went out of their way to use list.ForEach( delegate(item) { foo;});
instead of foreach(item in list) {foo; };
for all the code that they wrote. e.g. a block of code for reading rows from a dataReader.
I still don't know exactly why they did this.
The drawbacks of list.ForEach()
are:
It is more verbose in VS2005 and C# 2.0. However, in C# 3, you can use the "=>
" syntax to make some nicely terse expressions.
It is less familiar. People who have to maintain this code will wonder why you did it that way. It took me awhile to decide that there wasn't any reason, except maybe to make the writer seem clever (the quality of the rest of the code undermined that). It was also less readable, with the "})
" at the end of the delegate code block.
See also Bill Wagner's book "Effective C#: 50 Specific Ways to Improve Your C#" where he talks about why foreach is preferred to other loops like for or while loops - the main point is that you are letting the compiler decide the best way to construct the loop. If a future version of the compiler manages to use a faster technique, then you will get this for free by using foreach and rebuilding, rather than changing your code.
a foreach(item in list)
construct allows you to use break
or continue
if you need to exit the iteration or the loop. But you cannot alter the list inside a foreach loop.
I'm surprised to see that list.ForEach
is slightly faster. But that's probably not a valid reason to use it throughout, that would be premature optimisation. If your application uses a database or web service that, not loop control, is almost always going to be be where the time goes.
I disagree that the list.foreach(delegate)
version is "more functional". This might look superficially more like how a functional language would do it, but there's no big difference in what happens.
I don't think that foreach(item in list)
"says exactly how you want it done" - a for(int 1 =0; i < count; i++)
loop does that, a foreach loop leaves the choice of control up to the compiler.
My feeling now would be, on a new project, to use foreach(item in list)
for most loops in order to adhere to the common usage and for readability, and use list.Foreach()
only for short blocks, when you can do something more elegantly or compactly with the C#3 "=>" operator. In cases like that, there may already be a LINQ extension method that is preferable to ForEach()