I ran into this when I was investigating functional programming in C#. That’s been around for a while, but apart from using it for traversing or modifying collections or lists, I never actually created something that was making use of a function parameter.
Anyway, one of my most used constructs is the ForEach<T> method of List<T>. I always thought it to be quite annoying that it is only available for List<T>. Not for IList<T>, ICollection<T>, or whatever. Using my trademark solution pattern – the extension method ;-)
I tried the following:
using System; using System.Collections.Generic; namespace LocalJoost.Utilities { public static class GenericExtensions { public static void ForEach<T>(this IEnumerable<T> t, Action<T> action) { foreach (var item in t) { action(item); } } } }
And that turned out to be all. IList<T>, ICollection<T>, everything that implements IEnumerable<T> – now sports a ForEach method. It even works for arrays, so if you have something like this
string[] arr = {"Hello", "World", "how", "about", "this"}; arr.ForEach(Console.WriteLine);It nicely prints out
Hello
World
how
about
this
I guess it's a start. Maybe it is of some use to someone, as I plod on ;-)
2 comments:
Nice one! Will follow up on those posts, finally learning what Extensions are all about :)
Everyone who writes higher order functions (=functions that take other functions as parameters and/or return functions) must have written this ForEach extension method on IEnumerable for himself already.
Think I saw a blog post about the reason why it isn't in the BCL already (something to do with duplicating the foreach statement or something, giving people more than one way to do the exact same thing, which could get confusing), but I think it should have been in the BCL. Or List.ForEach() should not have existed, right?
Post a Comment