Pred is a whaticate? Generics on Steroids - Part II of II
If your application has a requirement that a certain number of user's need to be selected and then all of them promoted/demoted to a certain position within the company you would probably, again, have to iterate through your pre-filtered EmployeeCollection and change each user's department while performing the iteration. Although this is not difficult, it isn't something that is highly reusable and the code just looks plain nasty. This is where .NET 2.0 Actions come into play nicely and also allow for some reusability of business processes throughout your code. First, let's create a method that our Action will point to:
private void PromoteEmployeeToExecutive(Employee e)
{
Console.WriteLine("Promoting Employee {0} to CEO.", new object[] { e.Id });
e.Department = "CEO";
}
This is fairly simple method. It takes the Employee object that is receives and changes the department property to CEO. Nothing to it. Now, take a look at the .NET 2.0 Action we need to create to that points to this method:
private Action<Employee> promoteToExecutive = new Action<Employee>(PromoteEmployeeToExecutive);
Here we are instantiating an Action of type Employee called promoteToExecutive. This action is then pointed to the method we created above called PromoteEmployeeToExecutive. Thus, anytime our code uses the promoteToExecutive Action, the PromoteEmployeeToExecutive is called. Take a look at the implementation:
[Test]
public void PromoteAllToExecutives()
{
EmployeeCollection employees = FromXml();
employees.ForEach(promoteToExecutive);
}
The FromXml() method is just a method that is importing the xml file from the previous article into my custom EmployeeCollection object. When the data has been imported, we then call the ForEach method on the EmployeeCollection and pass it the promoteToExecutive Action instance. By doing this, every single Employee within the EmployeeCollection will have their respective Department properties set to CEO. Simple as that.