Anonymous Predicates :: Anonymous Actions - Pred's a Whaticate extra.
A commentator on my last series of posts requested some information on how to use anonymous methods within predicates. So, here goes:
For the sake of review, let's take a quick look at what an anonymous method is in .NET 2.0 (a strict 2.0 feature).
Basically, an anonymous method is a method that has no name and therefore it is anonymous. That should wrap this post up. Tune in tomorrow.
Just kidding.
First off, you need to have a good understanding of delegates to know what an anonymous method can do for you. In short, a delegate is a pointer to a method that is typically used within events or executing code across different threads.
However, the downside to a delegate is that sometimes I found myself creating a method just for the purpose of being referenced by a delegate. That got annoying because the method served no purpose outside of its respective delegate. So, let's check out how we can use an anonymous method within the declaration of a predicate:
private Predicate<Employee> accounting = delegate(Employee e)
{
return (e.Department == "Accounting");
};
This almost looks the same as what we had previously declared in part 1 of my previous post except you can see that rather than have the accounting Predicate point to the 'IsInAccountingDepartment' method, we actually have the method code inside that accounting Predicate itself using the brackets. Thus, the code used in the IsInAccountDepartment method is now actually part of the Predicate signature.
This exact same design can be used within Actions as well.