Lambda Expressions
A lambda expression is an unnamed method written in place of a delegate instance. The compiler immediately converts the lambda expression to either:
A delegate instance.
An expression tree, of type
Expression<TDelegate>, representing the code inside the lambda expression in a traversable object model. This allows the lambda expression to be interpreted later at runtime (we describe the process in Chapter 8 of C# 5.0 in a Nutshell).
Given the following delegate type:
delegate int Transformer (int i);
we could assign and invoke the lambda expression x => x * x as follows:
Transformer sqr = x => x * x;
Console.WriteLine (sqr(3)); // 9Note
Internally, the compiler resolves lambda expressions of this type by writing a private method, and moving the expression’s code into that method.
A lambda expression has the following form:
(parameters) =>expression-or-statement-block
For convenience, you can omit the parentheses if and only if there is exactly one parameter of an inferable type.
In our example, there is a single parameter, x, and the expression is x * x:
x => x * x;
Each parameter of the lambda expression corresponds to a delegate
parameter, and the type of the expression (which may be void) corresponds to the return type of the
delegate.
In our example, x corresponds to
parameter i, and the expression
x * x corresponds to the return type
int, therefore being compatible with
the Transformer delegate.
A lambda expression’s code can be a statement block instead of an expression. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access