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
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)); // 9
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:
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
In our example,
x corresponds to
i, and the expression
x * x corresponds to the return type
int, therefore being compatible with
A lambda expression’s code can be a statement block instead of an expression. ...