In this post I am going to introduce you to the Action<T> generic delegate and how you can use it with the ForEach(…) method that is exposed on collection classes. In earlier posts on the Comparison<T> and Predicate<T> I showed how these new features could be put to good use to make your code more expressive. In this instance however I feel that the Action<T> delegate and the ForEach method are really only “sometimes code” – if you can refute that then please leave a comment – I’d love to hear about your use case.

For your reference, the Action<T> delegate is defined as:

public delegate void Action<T>(T obj);

We then pass an instance of this delegate into the ForEach(…) method of a generic collection class (like List<T>). What happens then is that each element in the collection is enumerated and passed as the argument to the delegate. So if you combined anonymous methods with this feature you would end up with the following code.

ForEach

To me, that code doesn’t appear to be any more readable than the good old fashioned foreach(…) construct that you find in the VB.NET and C# languages (among others). So maybe the scenario I’ve chosen is wrong? Well, it turns out that the ForEach(…) method might be useful for those smaller inline pieces of logic, like printing something out to the screen.

ForEachSmall

I guess I’m still not convinced, but I would love to hear the opinion of other people. Anyway - you can download the code for this sample over at Project Distributor.