This is a mirror of official site: http://jasper-net.blogspot.com/

Lambda Expressions, Func and Action Delegates

| Thursday, August 18, 2011
Func and Action Delegates take the C# language to a new functional programming level. Lambda Expressions are tightly entwined in the LINQ infrastructure. We take a brief look at each.

Lambda Expressions

A lambda expression is an unnamed method that you write 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. 

Given the following delegate type:
delegate int Squarer (int i);
we could assign and invoke the lambda expression x => x * x as follows:
Squarer sqr = x => x * x;
Console.WriteLine (sqr(3));   

Lambda expressions are simply definitions of functions, but in a very concise form with little syntactical ceremony. Because the underlying platform supports delegates as a way to pass pieces of code around, lambda expressions can leverage this infrastructure and be converted into delegates. The following example illustrates the creation of a function that adds two numbers together, with and without the use of lambdas:

// C# 2.0 
Func<int, int, int> add20 = delegate (int a, int b) { return a + b; };

// C# 3.0 
Func<int, int, int> add30 = (a, b) => a + b;


A lambda expression has the following form:
(parameters) => expression-or-statement-block

You can omit the parentheses if there is only one parameter of an inferable type. In the 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.


Read more: eggcafe
QR: lambda-expressions-func-and-action-delegates.aspx

Posted via email from Jasper-net

0 comments: