foreach keyword or ForEach extension method?
Is this a question of taste, or something more serious? [Warning: this post won’t change your life J]
I found myself writing the following extension method yet again the other day;
public static void ForEach<T>(
this IEnumerable<T> source,
Action<T> action)
{
foreach (T item in source)
{
action(item);
}
}
This means I can write simple (contrived) code like the following;
entities.ForEach<ObjectDefinition>(o => o.DeleteDbRecord());
This will enumerate all my ObjectDefinition objects and call DeleteDbRecord on each. But why didn’t I just write it like this?
foreach (ObjectDefinition o in entities)
{
o.DeleteDbRecord();
}
I’ve raised this because some code I’ve seen (and written!) has reached a saturation point, where lambdas, extension methods, and other concepts have taken over - meaning the code looks more like it was written in LISP than C#.
But does that matter?
A quick search shows there are all sorts of discussions about this online, which is interesting. It is actually quite an old discussion now!