The result is returned. The second declaration assigns to
416
P a r t I :
T h e C # L a n g u a g e
true if the argument is even and false otherwise. Thus, it is compatible with the
IsEven
delegate declaration.
At this point, you might be wondering how the compiler knows the type of the data
used in a lambda expression. For example, in the lambda expression assigned to
incr
, how
does the compiler know that
count
is an
int
? The answer is that the compiler infers the type
of the parameter and the expression’s result type from the delegate type. Thus, the lambda
parameters and return value must be compatible with the parameter type(s) and return type
of the delegate.
Although type inference is quite useful, in some cases, you might need to explicitly
specify the type of a lambda parameter. To do so, simply include the type name. For
example, here is another way to declare the
incr
delegate instance:
Incr incr = (int count) => count + 2;
Notice now that
count
is explicitly declared as an
int
. Also notice the use of parentheses.
They are now necessary. (Parentheses can be omitted only when exactly one parameter is
specified and no type specifier is used.)
Although the preceding two lambda expressions each used one parameter, lambda
expressions can use any number, including zero. When using more than one parameter you
must
enclose them within parentheses. Here is an example that uses a lambda expression to
determine if a value is within a specified range:
(low, high, val) => val >= low && val <= high;
Here is a delegate type that is compatible with this lambda expression:
delegate bool InRange(int lower, int upper, int v);
Thus, you could create an
InRange
delegate instance like this:
InRange rangeOK = (low, high, val) => val >= low && val <= high;
After doing so, the lambda expression can be executed as shown here:
if(rangeOK(1, 5, 3)) Console.WriteLine("3 is within 1 to 5.");
One other point: Lambda expressions can use outer variables in the same way as
anonymous methods, and they are captured in the same way.
Statement Lambdas
As mentioned, there are two basic flavors of the lambda expression. The first is the expression
lambda, which was discussed in the preceding section. As explained, the body of an
expression lambda consists solely of a single expression. The second type of lambda
expression is the
statement lambda.
A statement lambda expands the types of operations that
can be handled within a lambda expression because it allows the body of lambda to contain
multiple statements. For example, using a statement lambda you can use loops,
if
statements,
declare variables, and so on. A statement lambda is easy to create. Simply enclose the body
within braces. Aside from allowing multiple statements, it works much like the expression
lambdas just discussed.
www.freepdf-books.com