Saturday, 4 February 2012

C# Array ForEach Method

I was recently looking at the two delegate types that the .NET BCL provides, namely, the Action(Of T) and Func(Of TResult) delegates - both can be found in the System namespace.

This post is primarily about the Action<T> delegate. You can use this delegate to store references to methods that return nothing (void) but have parameters. There are sixteen versions of this delegate, each taking an added parameter of type T (meaning you can store references to methods of up to sixteen parameters).

Both of these delegate types are provided as a convenience for the programmer. You could easily define your own delegate for your methods but it's now probably better practice to use Action<T> or Func<T, TResult> whenever you can. The example I wrote below uses Action<T> to create a nice little extension method for C# arrays (System.Array). It mimics the ForEach method on System.Collections.Generic.List<T>...

public static void ForEach<T>(this T[] sourceArray, Action<T> action)
{
    foreach (T obj in sourceArray)   
        action(obj);
}
You now have a cool way to perform an action on each item of an array without having to iterate through your array using a for loop or a foreach construct. The example use below defines a string array, then calls the ForEach, passing it a lambda expression that prints each item to console :

string[] cars = {"Porsche", "Ferrari", "Mercedes"};
cars.ForEach(c => Console.WriteLine(c));
You could also pass in an anonymous method or a named method if you don't like lambda expressions. The following example call uses an anonymous method:

cars.ForEach(delegate(string car) {
    Console.WriteLine(car);
});