Thursday, March 08, 2007 2:42 PM
Last time we talked about the Predicate object and how we could use it to identify which items of an array match our qualifications. Today we're going to talk about the Predicate's not-so-distant cousin, the Action object and how we can quickly perform an operation against every element in an array.
Action, like Predicate, is simply a delegate that we can pass into certain functions. Whatever 'action' is specified in Action, is performed on each member of the given collection. Taking our litter of Cat objects, we can pass our Pet delegate to each member of the litter which will 'Pet' each Cat.
{
Cat[] litter = new Cat[] { new Cat("Lucky"), new Cat("Frisky"), new Cat("Clyde") };
Array.ForEach<Cat>(litter, new Action<Cat>(Pet));
}
private void Pet(Cat cat)
{
Console.WriteLine("Pet " + cat.Name);
}
The code you see above will produce the following output (note the triumphant return of Lucky and Frisky)...
Pet Lucky
Pet Frisky
Pet Clyde
As you can see, by simply wrapping the Pet method in an Action delegate and passing it to our ForEach method we were able to perform the action to every object in the litter array.
That's all there is to it. But wait, Pet is kind of a simple method, could we avoid the code bloat of writing an entirely new method just to perfom Pet? Sure we can! We can simply create an anonymous method inline of our ForEach() arguments...
Array.ForEach<Cat>(litter, delegate(Cat cat)
{
Console.WriteLine("Pet " + cat.Name);
});
Voila! Now we have our code written inline. And with C# 3.0 slowly making its way into many developer's hands, where there's an anonymous delegate...there's a lamba expression!
Array.ForEach<Cat>(litter,
cat => Console.WriteLine("Pet " + cat.Name);
All three of these examples produce the exact same output.
There's something else here that's worth mentioning, however. We typically use an Array for each of these examples, but these delegates are not restricted for use only on a classical array. Both the FindXXX methods we discussed last time as well the ForEach method are also available off of the more commonly generic List<T> class. This means that its incredibly easy to incorporate these new techniques in your real world collections!