Lambda Expressions (C# 3.0)
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# 3.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
Note
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:
delegate int Transformer (int i);
A lambda expression’s code can ...
Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.