CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
}
Console.ReadLine();
static void TraditionalDelegateSyntax()
{
// Make a list of integers.
List list = new List();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
// Call FindAll() using traditional delegate syntax.
Predicate callback = new Predicate(IsEvenNumber);
List evenNumbers = list.FindAll(callback);
Console.WriteLine("Here are your even numbers:");
foreach (int evenNumber in evenNumbers)
{
Console.Write("{0}\t", evenNumber);
}
Console.WriteLine();
}
}
// Target for the Predicate<> delegate.
static bool IsEvenNumber(int i)
{
// Is it an even number?
return (i % 2) == 0;
}
Here, we have a method (IsEvenNumber()) that is in charge of testing the incoming integer
parameter to see whether it is even or odd via the C# modulo operator, %. If you execute your
application, you will find the numbers 20, 4, 8, and 44 print out to the console.
While this traditional approach to working with delegates behaves as expected, the IsEvenNumber()
method is invoked only in very limited circumstances—specifically when we call FindAll(), which leaves
us with the baggage of a full method definition. If we were to instead use an anonymous method, our
code would clean up considerably. Consider the following new method of the Program class:
static void AnonymousMethodSyntax()
{
// Make a list of integers.
List list = new List();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
// Now, use an anonymous method.
List evenNumbers = list.FindAll(delegate(int i)
{ return (i % 2) == 0; } );
Console.WriteLine("Here are your even numbers:");
foreach (int evenNumber in evenNumbers)
{
Console.Write("{0}\t", evenNumber);
}
391