CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
}
Console.WriteLine("AboutToBlow event was fired {0} times.",
aboutToBlowCounter);
Console.ReadLine();
After you run this updated Main() method, you will find the final Console.WriteLine() reports the
AboutToBlow event was fired twice.
Source Code The AnonymousMethods project is located under the Chapter 10 subdirectory.
Understanding Lambda Expressions
To conclude our look at the .NET event architecture, we will examine C# lambda expressions. As just
explained, C# supports the ability to handle events “inline” by assigning a block of code statements
directly to an event using anonymous methods, rather than building a stand-alone method to be called
by the underlying delegate. Lambda expressions are nothing more than a very concise way to author
anonymous methods and ultimately simplify how we work with the .NET delegate type.
To set the stage for our examination of lambda expressions, create a new Console Application
named SimpleLambdaExpressions. To begin, consider the FindAll() method of the generic List
class. This method can be called when you need to extract out a subset of items from the collection, and
is prototyped like so:
// Method of the System.Collections.Generic.List class.
public List FindAll(Predicate match)
As you can see, this method returns a new List that represents the subset of data. Also notice
that the sole parameter to FindAll() is a generic delegate of type System.Predicate. This delegate can
point to any method returning a bool, and takes a single type parameter as the only input parameter:
// This delegate is used by FindAll() method
// to extract out the subset.
public delegate bool Predicate(T obj);
When you call FindAll(), each item in the List is passed to the method pointed to by the
Predicate object. The implementation of said method will perform some calculations to see whether
the incoming data matches the necessary criteria, and return true or false. If this method returns true,
the item will be added to the new List that represents the subset (got all that?).
Before we see how lambda expressions can simplify working with FindAll(), let’s work the problem
out in longhand notation, using the delegate objects directly. Add a method (named
TraditionalDelegateSyntax()) within your Program type that interacts with the System.Predicate
type to discover the even numbers in a List of integers:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Lambdas *****\n");
TraditionalDelegateSyntax();
390