Are there advantages to either approach? If I need to traverse List items and perform an action on each one, should I use the traditional foreach loop mechanism or move on to List.ForEach?
Matthew Podwysocki @ CodeBetter.com wrote an interesting article about the anti-for campaign. This got me thinking about the problem a loop is trying to solve. In this article, Matthew argues that explicit loop structures make you think about the 'how' instead of the 'what'.
What are some good reasons to use one over the other (if there are any)?
For one thing, you'd use it if you'd been passed the delegate to apply for whatever reason. For example, you might create your own list, populate it etc and then apply a delegate to each entry. At that point, writing:
list.ForEach(action);
is simpler than
foreach (Item item in list)
{
action(item);
}
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