C# in Depth

Cover of C# in Depth
Order now (3rd edition)

List.ForEach - friend or foe?

Chapter 1: The changing face of C# development: 1.1.3

Created: 1/22/2008
Last updated: 1/22/2008

Eric made an interesting comment on listing 1.11, where I demonstrate the ForEach method. His view is that expressions should be free from side effects wherever possible, and statements should be useful only for their side effects. That suggests that you should use the foreach statement to iterate through a collection and perform actions on it, rather than using an expression with a ForEach call.

Listing 1.12 shows the kind of code Eric is more in favour of, demonstrating (in his words) "shiny beauty". Every statement has a side effect, and every expression computes a value.

This is quite a purist viewpoint I suspect - and to be totally honest, I don't think I'm really qualified to discuss its merits. It's interesting to consider though - try applying it to your code, and see whether the results are clearer.