Lambda Expressions

In Listing 13.7 and Listing 13.11, we saw that you can convert the expressions GreaterThan and AlphabeticalGreaterThan to a delegate type that is compatible with the parameter types and the return type of the named method. You might have noticed that the declaration of the GreaterThan method—the code that says it is a public, static, bool-returning method with two parameters of type int named first and second—was considerably larger than the body of the method, which simply compared its two parameters and returned the result. It is unfortunate that so much ceremony must surround such a simple method merely so that it can be converted to a delegate type.

To address this concern, compact syntax exists for creating a delegate. When referring generally to anonymous methods or lambda expressions, we’ll refer to them as anonymous functions. Both syntaxes are still legal, but for new code, the lambda expression syntax is preferred over the anonymous method syntax.8

Lambda expressions are themselves divided into two types: statement lambdas and expression lambdas. Figure 13.2 shows the hierarchical relationship between these terms.