torsdag 16 oktober 2008

The ForEach extension method (C#)

Everyone knows about the foreach keyword, but have you ever noticed there are no equivalent extension method for IEnumerables? I.e. execute "this action" on each element. Perhaps the most simple extension method of them all, which is the reason I'll share it with you :)

public static class MyExtensionMethods
{
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
foreach(var item in list) action(item);
}
}

For you who aren't familiar with extension methods, what it really says is that, ForEach is a member method of IEnumerable<T>, and can be called by simply writing
myList.ForEach(myAction)

For example, to output each item of a list to the console, you could write:
myList.ForEach(x => Console.Write(x));

instead of
foreach(var x in in myList) Console.Write(x);

In this case you might not gain so much in terms of code size, but I think it makes the code more readable. You are reading text from left to right, so it makes sense having the for each statement to the right, right? :)
myList.WhereThis().SelectThat().DoThis();

(There is probably some kind of cool name for this pattern, like "The opposite of law of demeter"... Gustaf probably has more knowledge in this!)

Here is a more complex example of a combination of extension methods:
myList.Where(x => x.IsValid()).Select(x => x.ComputeValue()).Where(x => x > 0).ForEach(x => Console.Write(x));

Where and Select are also extension methods of IEnumerable. Without these you would have to write:

foreach(var x in myList)
{
if (x.IsValid())
{
var value = x.ComputeValue();
if (value > 0) Console.Write(value);
}
}

8 lines instead of 1! Impressed? :)

So, extension methods! Learn them, use them, and write your own!